1. 程式人生 > >【LeetCode】#130被圍繞的區域(Surrounded Regions)

【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);
                }
            }
        }
 
    }
}