【LeetCode】#130被围绕的区域(Surrounded Regions)

【LeetCode】#130被围绕的区域(Surrounded Regions)

题目描述

给定一个二维的矩阵,包含 ‘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’。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。

Description

Given a 2D board containing ‘X’ and ‘O’ (the letter O), capture all regions surrounded by ‘X’.
A region is captured by flipping all 'O’s into 'X’s in that surrounded region.

Example

X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Explanation:
Surrounded regions shouldn’t be on the border, which means that any ‘O’ on the border of the board are not flipped to ‘X’. Any ‘O’ that is not on the border and it is not connected to an ‘O’ on the border will be flipped to ‘X’. Two cells are connected if they are adjacent cells connected horizontally or vertically.

解法

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/weixin_43858604/article/details/85054602