题目描述:
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
题目分析:
首先找到从四个边界开始寻找O,将其进行标记。标记完后,对于剩余的的O就将其变为X,标记的进行还原即可。
代码:
class Solution {
public:
void solve(vector<vector<char>> &board) {
if(board.size()==0)return;
int row=board.size();
int col=board[0].size();
//up
for(int i=0;i<col;i++){
if(board[0][i]=='O'){
bfs(board,0,i);
}
}
//right
for(int i=0;i<row;i++){
if(board[i][col-1]=='O'){
bfs(board,i,col-1);
}
}
//down
for(int i=0;i<col;i++){
if(board[row-1][i]=='O'){
bfs(board,row-1,i);
}
}
//left
for(int i=0;i<row;i++){
if(board[i][0]=='O'){
bfs(board,i,0);
}
}
//modify
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(board[i][j]=='+'){
board[i][j]='O';
} else if(board[i][j]=='O'){
board[i][j]='X';
}
}
}
}
//search bounds
void bfs(vector<vector<char>> &board, int i, int j) {
queue<int> q;
int col=board[0].size();
visit(board,i,j,q);
while(!q.empty()){
int cur=q.front();
q.pop();
int x=cur/col;
int y=cur%col;
visit(board,x-1,y,q);
visit(board,x,y-1,q);
visit(board,x+1,y,q);
visit(board,x,y+1,q);
}
}
void visit(vector<vector<char>> &board, int i, int j, queue<int> &q) {
int m = board.size();
int n = board[0].size();
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O')
return;
board[i][j] = '+';
q.push(i * n + j);
}
};