LeetCode130. 被围绕的区域

题目

给定一个二维的矩阵,包含 'X' 和 'O'字母 O)。

找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O''X' 填充。

示例:

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

解释:

被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。


分析

深度广度优先题目,原解题报告链接 点击打开链接

大概思路是,只要把不和边界O连通的 O 换位X就可以了。所以我们只需要遍历一下四条边,将于边界O相连的O做上标记,最后遍历char[][]数组,来改变一下字母和符号就可以了。

在找到边界O时,需要向它的四周去找和它相通的O,这里就用到了队列,被连通的O的坐标首先入队,然后出队,判断它的四周是否有连通的O,入队,再出队,判断是否有连通的O……直到队列中没有元素。


代码

class Solution {
    public void solve(char[][] board) {
        if(board.length == 0 ) return;
        int row = board.length;
        int col = board[0].length;
        
        for (int i = 0; i < row; i++) {
            if (board[i][0] == 'O') helper(board,i,0);
            if (board[i][col-1] == 'O') helper(board,i,col-1);
        }

        for (int i = 0; i < col; i++) {
            if (board[0][i] == 'O') helper(board,0,i);
            if (board[row-1][i] == 'O') helper(board,row-1,i); 
        }
        
        for (int i = 0; i < row; i++)
            for (int j = 0; j < col; j++) {
                if (board[i][j] == 'O') board[i][j] = 'X';
                else if (board[i][j] == '*') board[i][j] = 'O';
            }

    }
    
    public static void helper( char[][] board , int x, int y ){

        int[][] nums = {{0,1},{0,-1},{1,0},{-1,0}};
        Queue<Integer[]> queue = new LinkedList<>();
        Integer[] integers = {x,y};
        queue.offer(integers);
        board[x][y] = '*';

        while ( queue != null && queue.size() != 0){
            Integer[] temp = queue.poll();
            for (int i = 0; i < 4; i++) {
                Integer newX = temp[0]+nums[i][0];
                Integer newY = temp[1]+nums[i][1];
                if (newX < 0 || newX >= board.length || newY < 0 || newY >= board[0].length) continue;

                if (board[newX][newY] == 'O'){
                    board[newX][newY] = '*';
                    Integer[] t = {newX, newY};
                    queue.offer(t);
                }
            }
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_38595487/article/details/80064168