Question:
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
Thought:
BFS, first go through 4 bounds of the matrix, if ‘O’ found, do BFS to mark all adjacent ‘O’ to ‘Y’. (These ‘O’ will not be surrounded by ‘X’)
Then we iterate matrix again, mark all ‘O’=’X’, all ‘Y’=’O’.
Note, we use a boolean matrix to mark the visited element in BFS, this will help program run faster. If we don’t use boolean matrix, same element will be enqueue more than once.
public void solve(char[][] board) {
if(board==null||board.length==0||board[0].length==0) return;
int row=board.length;
int col=board[0].length;
boolean [][] isVisited = new boolean[row][col];
for(int i=0;i<col;i++){
mark(board,0,i,isVisited);
mark(board,row-1,i,isVisited);
}
for(int i=0;i<row;i++){
mark(board,i,0,isVisited);
mark(board,i,col-1,isVisited);
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(board[i][j]=='O'){
board[i][j]='X';
}
if(board[i][j]=='Y'){
board[i][j]='O';
}
}
}
}
public void mark(char[][]board,int x,int y,boolean[][] isVisited){
if(board[x][y]!='O') return;
Queue<Cor> q= new LinkedList<>();
q.add(new Cor(x,y));
int row=board.length;
int col=board[0].length;
while(!q.isEmpty()){
Cor c=q.poll();
board[c.x][c.y]='Y';
isVisited[c.x][c.y]=true;
if(c.x-1>=0&&board[c.x-1][c.y]=='O'&&!isVisited[c.x-1][c.y]){
q.add(new Cor(c.x-1,c.y));
isVisited[c.x-1][c.y]=true;
}
if(c.x+1<row&&board[c.x+1][c.y]=='O'&&!isVisited[c.x+1][c.y]){
q.add(new Cor(c.x+1,c.y));
isVisited[c.x+1][c.y]=true;
}
if(c.y-1>=0&&board[c.x][c.y-1]=='O'&&!isVisited[c.x][c.y-1]){
q.add(new Cor(c.x,c.y-1));
isVisited[c.x][c.y-1]=true;
}
if(c.y+1<col&&board[c.x][c.y+1]=='O'&&!isVisited[c.x][c.y+1]){
q.add(new Cor(c.x,c.y+1));
isVisited[c.x][c.y+1]=true;
}
}
}
public class Cor{
int x;
int y;
public Cor(int x, int y){
this.x=x;
this.y=y;
}
}