2014年12月2日星期二

[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

Using BFS from the 'O' on the boundary and find all 'O' that could be connected, that is the connected component. All 'O' expect these in the connected component would be surrounded by 'X' and mark them as 'X'.

    public void solve(char[][] board) {
        int m = board.length;
        if(m == 0)
            return ;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        Queue<Integer> qx = new LinkedList<Integer>();
        Queue<Integer> qy = new LinkedList<Integer>();
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        for(int i = 0; i < n; i++) {
            if(board[0][i] == 'O') {
                qx.add(0); qy.add(i);
                visited[0][i] = true;
            }
            if(board[m-1][i] == 'O') {
                qx.add(m-1); qy.add(i);
                visited[m-1][i] = true;
            }
        }
        for(int i = 1; i < m-1; i++) {
            if(board[i][0] == 'O') {
                qx.add(i); qy.add(0);
                visited[i][0] = true;
            }
            if(board[i][n-1] == 'O') {
                qx.add(i); qy.add(n-1);
                visited[i][n-1] = true;
            }
        }
        while(qx.size() != 0) {
            int x = qx.remove();
            int y = qy.remove();
            for(int i = 0; i < 4; i++) {
                int xx = x + dx[i];
                int yy = y + dy[i];
                if(xx >= 0 && xx < m && yy >= 0 && yy < n && board[xx][yy] == 'O' && visited[xx][yy] == false) {
                    qx.add(xx); qy.add(yy);
                    visited[xx][yy] = true;
                }
            }
        }
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(board[i][j] == 'O' && visited[i][j] == false)
                    board[i][j] = 'X';
            }
        }
    }

没有评论:

发表评论