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
题目分析:
有两种切入点,一种是查找被围起来的区域,将他们标成’X’,另一种是找边界上的’O’,用排除法,剩下的就是被围起来的区域。
这两种方法都可以用BFS实现,我使用了找边界上与’O’连通的区域,将他们存储到一个队列中,然后使用BFS,找到所有的连通点,设置一个特殊的标志’-‘,最后遍历一遍,将所有的’O’改为’X’,将所有的’-‘改为’O’。
代码实现:
class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.size() == 0)
return;
int row(board.size()), col(board[0].size()), r, c;
queue<int> index_x, index_y;
for(int i = 0; i < col; ++i) {
if(board[0][i] == 'O') {
index_x.push(0);
index_y.push(i);
}
if(board[row-1][i] == 'O') {
index_x.push(row-1);
index_y.push(i);
}
}
for(int i = 1; i < row-1; ++i) {
if(board[i][0] == 'O') {
index_x.push(i);
index_y.push(0);
}
if(board[i][col-1] == 'O') {
index_x.push(i);
index_y.push(col-1);
}
}
while(!index_x.empty()) {
r = index_x.front();
c = index_y.front();
index_x.pop();
index_y.pop();
board[r][c] = '-';
if(r > 0 && board[r-1][c] == 'O') {
index_x.push(r-1);
index_y.push(c);
}
if(r < row-1 && board[r+1][c] == 'O') {
index_x.push(r+1);
index_y.push(c);
}
if(c > 0 && board[r][c-1] == 'O') {
index_x.push(r);
index_y.push(c-1);
}
if(c < col-1 && board[r][c+1] == 'O') {
index_x.push(r);
index_y.push(c+1);
}
}
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] == '-')
board[i][j] = 'O';
}
}
}
};