LeetCode题解:Surrounded Regions

Given a 2D board containing ‘X’ and ‘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

题意:给定由X和O组成的二维数组,将所有被X包围的O替换成X

解决思路:BFS和DFS都可以

代码:

public class Solution {
    private int row = 0;
    private int col = 0;
    private Queue<Integer> queue = new LinkedList<Integer>();

    public void solve(char[][] board) {
        if(board == null || board.length == 0){
            return;
        }

        row = board.length;
        col = board[0].length;
        boolean[][] mark = new boolean[row][col];

        for(int i = 0; i < row; i++){
            bfs(i, 0, board, mark);
            bfs(i, col - 1, board, mark);
        }

        for(int i = 0; i < col; i++){
            bfs(0, i, board, mark);
            bfs(row - 1, i, board, mark);
        }

        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] == 'C'){
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void bfs(int x, int y, char[][] board, boolean[][] mark){
        mark(x, y, board, mark);

        while(!queue.isEmpty()){
            int curr = queue.poll();
            int xPos = curr / col;
            int yPos = curr % col;

            mark(xPos + 1, yPos, board, mark);
            mark(xPos, yPos + 1, board, mark);
            mark(xPos - 1, yPos, board, mark);
            mark(xPos, yPos - 1, board, mark);
        }
    }

    private void mark(int x, int y, char[][] board, boolean[][] mark){
        if(x < 0 || y < 0 || x >= row || y >= col || mark[x][y] == true || board[x][y] != 'O'){
            return;
        }

        mark[x][y] = true;
        board[x][y] = 'C';
        queue.offer(x * col + y);
    }
}

你可能感兴趣的:(LeetCode)