题目描述:
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’,进行BFS搜索,将跟边界接触且为‘O’的元素进行标记为‘+’,之后对标记为‘+’的元素进行替换为‘O’。
代码如下:
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);
}
}
//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);
}
}
//right
for(int i=0;i<row;i++){
if(board[i][col-1]=='O'){
bfs(board,i,col-1);
}
}
//change
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';
}
}
}
return ;
}
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 + 1, y, q);
visit(board, x, y - 1, 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);
}
};