题目:
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
思路:
一开始我尝试从外向里一层一层的递推,但是感觉代码比较臃肿。所以后来选择了BFS的算法,即从最外一圈找到字符为O的入口,向内做BFS。为了不重复遍历相同的单元格,我利用了board这个矩阵本身来保存每个单元格访问的状态, Y表示访问过的O单元格、V表示访问过的X单元格。
代码:
class Solution {
public:
void solve(vector<vector<char>> &board) {
if(board.size()==0||board[0].size()==0)
{
return;
}
else if(board.size()<=2||board[0].size()<=2)
{
return;
}
else
{
for(int i=0;i<board.size();i++)
{
goDeep(board,i,0);
goDeep(board,i,board[i].size()-1);
}
for(int j=0;j<board[0].size();j++)
{
goDeep(board,0,j);
goDeep(board,board.size()-1,j);
}
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[i].size();j++)
{
if(board[i][j]=='Y')
{
board[i][j]='O';
}
else
{
board[i][j]='X';
}
}
}
}
}
void goDeep(vector<vector<char>> &board, int x, int y)
{
if(board[x][y] != 'V' && board[x][y] != 'Y')
{
if(board[x][y]=='O')
{
board[x][y]='Y';
if(x > 0)
goDeep(board,x-1,y);
if(x < board.size() - 2)
goDeep(board,x+1,y);
if(y > 0)
goDeep(board,x,y-1);
if(y < board[0].size() - 2)
goDeep(board,x,y+1);
}
else{
board[x][y] = 'V';
}
}
}
};