被围绕的区域——leetcode130(DFS)

被围绕的区域

题目:被围绕的区域

给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。

示例:

输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]

题解:DFS

从边界的O开始,找出所有相连的O。没被找到的就是被X包围的O

class Solution {
    public void dfs(int[][] book, char[][] board, int x, int y) {
        if (x < 0 || x >=board.length || y < 0 || y >=board[0].length || book[x][y] == 1 || board[x][y]=='X') {
            return;
        }
        book[x][y] = 1;
        dfs(book, board, x + 1, y);
        dfs(book, board, x - 1, y);
        dfs(book, board, x, y + 1);
        dfs(book, board, x, y - 1);
    }

    public void solve(char[][] board) {
        int[][] book = new int[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (i == 0 || j == 0 || i == board.length - 1 || j == board[0].length - 1) {
                    if (board[i][j] == 'O') {
                        dfs(book, board, i, j);
                    }
                }
            }
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'O' && book[i][j] == 0) {
                    board[i][j] = 'X';
                }
            }
        }
    }
}

 

posted @ 2022-01-10 12:28  言思宁  阅读(24)  评论(0编辑  收藏  举报