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
这道题让我这个小白对于BFS又有了一定的理解
class Solution {
public:
void solve(vector<vector<char>>& board) {
int row=board.size();
if(row==0)
return;
int col=board[0].size();
for(int i=0;i<row;i++){
judge(i,0,board,row,col);
if(col>1)
judge(i,col-1,board,row,col);
}
for(int j=0;j<col;j++){
judge(0,j,board,row,col);
if(row>1)
judge(row-1,j,board,row,col);
}
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
board[i][j]=board[i][j]=='.'?'O':'X';
}
void judge(int i,int j,vector<vector<char>>& board,int row,int col){
if(board[i][j]=='O'){
board[i][j]='.';
if(i-1>0)
judge(i-1,j,board,row,col);
if(i+1<row)
judge(i+1,j,board,row,col);
if(j-1>0)
judge(i,j-1,board,row,col);
if(j+1<col)
judge(i,j+1,board,row,col);
}
}
};