算法

LCP 41. 黑白翻转棋

2023-06-20  本文已影响0人  红树_

LC每日一题,参考LCP 41. 黑白翻转棋

题目

n*m 大小的棋盘中,有黑白两种棋子,黑棋记作字母 "X", 白棋记作字母 "O",空余位置记作 "."。当落下的棋子与其他相同颜色的棋子在行、列或对角线完全包围(中间不存在空白位置)另一种颜色的棋子,则可以翻转这些棋子的颜色。若下一步可放置一枚黑棋,请问选手最多能翻转多少枚白棋。
注意:

输入:chessboard = [".X.",".O.","XO."]
输出:2

输入:chessboard = [".......",".......",".......","X......",".O.....","..O....","....OOX"]
输出:4

提示:

解题思路

深度优先搜索

class Solution {
    int n,m;
    String[] chessboard;
    public int flipChess(String[] chessboard) {
        this.chessboard = chessboard;
        n = chessboard.length;
        m = chessboard[0].length();
        int ans = 0;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(chessboard[i].charAt(j) == '.') { //可以放置黑棋
                    ans = Math.max(ans,get(i,j,newC()));
                }
            }
        }
        return ans;
    }
    //创建新的棋盘拷贝
    char[][] newC() {
        char[][] c = new char[n][m];
        for(int i = 0; i < n; i++) c[i] = chessboard[i].toCharArray();
        return c;
    }
    int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};
    //在i,j位置放置黑棋翻转的白棋数
    int get(int i, int j,char[][] cb) {
        int count = 0;
        //判断周围有没有白棋
        for(int[] dir : dirs) {
            int ni = i + dir[0], nj = j + dir[1];
            if(ni >= 0 && nj >= 0 && ni < n && nj < m && cb[ni][nj] == 'O') {
                //往dir方向继续找看有没有黑棋
                count += check(dir,ni,nj,cb);
            }
        }
        return count;
    }
    //返回能翻转该方向白棋的数量
    int check(int[] dir, int i, int j,char[][] cb) {
        //判断终点是否有黑棋
        int ni = i + dir[0],nj = j + dir[1];
        while(ni >= 0 && nj >= 0 && ni < n && nj < m && cb[ni][nj] == 'O') {
            ni += dir[0];
            nj += dir[1];
        }
        if(!(ni >= 0 && nj >= 0 && ni < n && nj < m) || cb[ni][nj] != 'X') return 0;
        //翻转白棋 统计数量
        int count = 0;
        ni = i;
        nj = j;
        while(ni >= 0 && nj >= 0 && ni < n && nj < m && cb[ni][nj] == 'O') {
            cb[ni][nj] = 'X';
            count += 1 + get(ni,nj,cb);//递归获取该黑棋的翻转数
            ni += dir[0];
            nj += dir[1];
        }
        return count;
    }
}

复杂度分析

2023.06.21

上一篇 下一篇

猜你喜欢

热点阅读