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
实现题,没什么算法的,在边上找一圈,用DFS,把‘O’对应的区域换成‘#’,把‘O’换成‘X’
看评论好多人说不能AC,试了一下果真不行,那已经是两年前的实现了好不好。。。。leetcode增加了test case,于是用dfs重新实现了一遍,发现大数据过不了,一直runtime error,原因是调用栈溢出,所以用bfs重新实现了一遍,dfs的代码也没删,放在里面吧
这道题本质上就是一个图的遍历,但是比较特殊的是,图本身是可以改的,所以不需要一个visited的矩阵来保存,当把O换成#以后,就相当于在visited当中置位了。还需要注意一点的是,在bfs当中,需要先置位,再push Queue, 原因如上。
class Solution {
public:
void solve(vector<vector<char>> &board) {
if(board.empty()) return;
int M = board.size(), N = board[0].size();
int i,j;
//上面一行, 下面一行
for(int j = 0; j < N; j++){
i = 0;
if(board[i][j] == 'O'){
bfs(board, M, N, i, j);
}
i = M-1;
if(board[i][j] == 'O'){
bfs(board, M, N, i, j);
}
}
//左边一列,右边一列
for(int i = 0; i < M; i++){
j = 0;
if(board[i][j] == 'O'){
bfs(board, M, N, i, j);
}
j = N-1;
if(board[i][j] == 'O'){
bfs(board, M, N, i, j);
}
}
//把O换成X,把#换成O
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
} else if(board[i][j] == '#'){
board[i][j] = 'O';
}
}
}
}
void bfs(vector<vector<char>> &board, int M, int N, int x, int y){
queue<pair<int, int> > q;
board[x][y] = '#';
q.push(pair<int, int>(x,y));
while(!q.empty()){
int i = q.front().first;
int j = q.front().second;
q.pop();
pushQ(board, M, N, q, i-1, j);
pushQ(board, M, N, q, i+1, j);
pushQ(board, M, N, q, i, j-1);
pushQ(board, M, N, q, i, j+1);
}
}
//从i,j开始dfs
void dfs(vector<vector<char>> &board, int M, int N, int i, int j){
board[i][j] = '#';
//up
if(inMatrix(i-1,j, M, N) && board[i-1][j] == 'O'){
dfs(board, M, N, i-1, j);
}
//down
if(inMatrix(i+1,j, M, N) && board[i+1][j] == 'O'){
dfs(board, M, N, i+1, j);
}
//up
if(inMatrix(i,j-1, M, N) && board[i][j-1] == 'O'){
dfs(board, M, N, i, j-1);
}
//up
if(inMatrix(i,j+1, M, N) && board[i][j+1] == 'O'){
dfs(board, M, N, i, j+1);
}
}
void pushQ(vector<vector<char>> &board, int M, int N, queue<pair<int, int> > &q, int i, int j){
if(inMatrix(i,j, M, N) && board[i][j] == 'O'){
board[i][j] = '#';
q.push(pair<int, int>(i,j));
}
}
bool inMatrix(int i, int j, int M, int N){
return i>=0 && i < M && j>=0 && j < N;
}
};