clllll  

image

class Solution {
    public void solve(char[][] board) {
        // 思路:从边缘入手,遇到O.就渲染为'F',递归渲染其他O;
        // 再遍历 .遇到的O就可以都渲染为X.
        // 最后更新F为O;
        int m = board.length;
        int n = board[0].length;

        for (int i = 0; i < n; i++) {
            if (board[0][i] == 'O') {
                // 第一行
                f(0, i, board);
            }
            if (board[m - 1][i] == 'O') {
                // 最后一行
                f(m - 1, i, board);
            }
        }
        for (int j = 1; j < m - 1; j++) {
            if (board[j][0] == 'O') {
                // 第一列
                f(j, 0, board);
            }
            if (board[j][n - 1] == 'O') {
                // 最后一列
                f(j, n - 1, board);
            }
        }
        for (int j2 = 0; j2 < m; j2++) {
            for (int k = 0; k < n; k++) {

                if (board[j2][k] == 'O') {
                    // 遇到O就改为X
                    board[j2][k] = 'X';
                }
                if (board[j2][k] == 'F') {
                    // 遇到F 还原为O
                    board[j2][k] = 'O';
                }

            }

        }
    }

    public void f(int i, int j, char[][] board) {
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != 'O') {
            return;
        }
        board[i][j] = 'F';
        f(i + 1, j, board);
        f(i - 1, j, board);
        f(i, j + 1, board);
        f(i, j - 1, board);

    }
}
posted on 2024-12-05 22:40  llcl  阅读(5)  评论(0编辑  收藏  举报