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
Solution:
If we think it directly, it would be complicated. A easier way is think it in an opposite way.
What nodes will not be flipped?
BFS each 'O' on the edges, mark 'O's which can be visited from edged 'O'.
Tips: use a size 2 array to represent coordinates (x,y).
////////////////////////// bfs from edged 'O', and mark its surrounding 'O's, that will not be flipped. //////////////////////////
public class Solution {
public void solve(char[][] board) {
int m = board.length;
if(m == 0) return;
int n = board[0].length;
boolean[][] marked = new boolean[m][n];
// find edged 'O'.
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if((i == 0 || i == m-1 || j == 0 || j == n-1) && (!marked[i][j]))
if(board[i][j] == 'O')
dfs(i,j,m,n,board,marked);
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(!marked[i][j])
board[i][j] = 'X';
}
// mark it surrounding 'O' from edges
public void dfs(int i, int j, int m, int n, char[][] board, boolean[][] marked){
ArrayList queue = new ArrayList();
queue.add(new Integer[]{i, j});
marked[i][j] = true;
while(!queue.isEmpty()){
Integer[] tmp = queue.remove(0);
int x = tmp[0];
int y = tmp[1];
// not going to visit marked nodes to avoid infinite loops.
if(x - 1 >= 0 && board[x-1][y] == 'O' && !marked[x-1][y]){
queue.add(new Integer[]{x-1,y});
marked[x-1][y] = true;
}
if(x + 1 <= m-1 && board[x+1][y] == 'O' && !marked[x+1][y]){
queue.add(new Integer[]{x+1,y});
marked[x+1][y] = true;
}
if(y - 1 >= 0 && board[x][y-1] == 'O' && !marked[x][y-1]){
queue.add(new Integer[]{x,y-1});
marked[x][y-1] = true;
}
if(y + 1 <= n-1 && board[x][y+1] == 'O' && !marked[x][y+1]){
queue.add(new Integer[]{x,y+1});
marked[x][y+1] = true;
}
}
}
}
No comments:
Post a Comment