#leetcode#130. Surrounded Regions

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/77440375

iven 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.

For 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

--------------------------------------------

思路是flood fill,先把四条边上的O染色,把相邻O变成‘1’, 然后再遍历一般即可

class Solution {
    public void solve(char[][] board) {
        if(board == null || board.length < 2  || board[0].length < 2)
            return;
        int m = board.length; 
        int n = board[0].length;
        
        for(int i = 0; i < n; i++){
            fillEdge(board, 0, i);
            fillEdge(board, m - 1, i);
        }
        for(int j = 0; j < m; j++){
            fillEdge(board, j, 0);
            fillEdge(board, j, n - 1);
        }        
        
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(board[i][j] == 'O'){
                    board[i][j] = 'X';
                }else if(board[i][j] == '1'){
                    board[i][j] = 'O';
                }
            }
        }
    }
    
    private void fillEdge(char[][] board, int row, int col){
        if(board[row][col] != 'O'){
            return;
        }
        int m = board.length;
        int n = board[0].length;
        LinkedList<Integer> queue = new LinkedList<>();
        queue.offer(row * n + col);
        while(!queue.isEmpty()){
            int idx = queue.poll();
            int x = idx / n;
            int y = idx % n;
            if(x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O'){
                continue;
            }
            board[x][y] = '1';
            queue.offer((x + 1) * n + y);
            queue.offer((x - 1) * n + y);
            queue.offer(x * n + y + 1);
            queue.offer(x * n + y - 1);
        }
    }
    
}



猜你喜欢

转载自blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/77440375