Description:
Given a 2D board containing 'X'
and 'O'
(the letter 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
Solutions:
//用BFS遍历
class Solution {
public:
void solve(vector<vector<char> > &board) {
int row = board.size();
if(row == 0){
return;
}
int col = board[0].size();
if(row <= 2 || col <= 2){
return;
}
for(int i = 0;i < col;++i){
BFS(board,row,col,0,i);
BFS(board,row,col,row-1,i);
}
for(int j = 0;j < row;++j){
BFS(board,row,col,j,0);
BFS(board,row,col,j,col-1);
}
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] == '.'){
board[i][j] = 'O';
}
}
}
}
private:
void BFS(vector<vector<char>> &board,int row,int col,int x,int y){
queue<pair<int,int> > q;
Pass(board,row,col,x,y,q);
while(!q.empty()){
pair<int,int> point = q.front();
q.pop();
x = point.first;
y = point.second;
Pass(board,row,col,x,y+1,q);
Pass(board,row,col,x,y-1,q);
Pass(board,row,col,x-1,y,q);
Pass(board,row,col,x+1,y,q);
}
}
void Pass(vector<vector<char>> &board,int row,int col,int x,int y,queue<pair<int,int> > &q){
if(x < 0 || x >= row || y < 0 || y >= col || board[x][y] != 'O'){
return;
}
board[x][y] = '.';
q.push(make_pair(x,y));
}
};