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',变为其他字符'1',以作为标记。
1.是作为已访问标记。2.是作为连通标记。
当对外层所有节点完成上述操作后的。
再进行一次全体扫描,其中,如果值仍为'O',说明这些是被'X'包围的结点,不与边界上的'O'联通。则将其置为'X'。
如果其值为'1',说明是刚才bfs搜索过的节点,它们并未被'X'全部包围。则恢复其值为'O'。
在leetcode上实际执行时间为20ms.
class Solution {
public:
void solve(vector<vector<char>>& board) {
if (board.empty()) return;
const int row = board.size();
const int col = board[0].size();
const char C = '1';
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
if (i && j && i!=row-1 && j!=col-1 || board[i][j]=='X')
continue;
queue<pair<int, int> >q;
q.push(make_pair(i, j));
board[i][j] = C;
while (!q.empty()) {
int count = q.size();
while (count--) {
auto xy = q.front();
q.pop();
if (xy.first && board[xy.first-1][xy.second]=='O') {
board[xy.first-1][xy.second] = C;
q.push(make_pair(xy.first-1, xy.second));
}
if (xy.second && board[xy.first][xy.second-1]=='O') {
board[xy.first][xy.second-1] = C;
q.push(make_pair(xy.first, xy.second-1));
}
if (xy.first+1<row && board[xy.first+1][xy.second]=='O') {
board[xy.first+1][xy.second] = C;
q.push(make_pair(xy.first+1, xy.second));
}
if (xy.second+1<col && board[xy.first][xy.second+1]=='O') {
board[xy.first][xy.second+1] = C;
q.push(make_pair(xy.first, xy.second+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]==C)
board[i][j] = 'O';
}
}
}
};