Given a 2D board containing 'X'
and
'O'
(the letter 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设置为Y,然后在进行遍历board,将O设置为X,将Y设置为O
代码如下:
class Solution {
public:
class point
{
public:
int x;
int y;
point(int i,int j)
{
x=i;
y=j;
}
};
void solve(vector<vector<char>>& board) {
if(board.empty())
return;
int m = board.size();
int n = board[0].size();
queue<point*> data;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(j==0||j==n-1||i==0||i==m-1)
{
if(board[i][j] == 'O')
{
board[i][j] = 'Y';
data.push(new point(i,j));
}
}
}
while(!data.empty())
{
point* now = data.front();
data.pop();
int x = now->x;
int y = now->y;
board[x][y] = 'Y';
if(x+1<m && board[x+1][y] == 'O' )
data.push(new point(x+1,y));
if(x-1>=0 && board[x-1][y] == 'O' )
data.push(new point(x-1,y));
if(y+1<n && board[x][y+1] == 'O' )
data.push(new point(x,y+1));
if(y-1>=0 && board[x][y-1] == 'O' )
data.push(new point(x,y-1));
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(board[i][j] == 'Y')
board[i][j] = 'O';
else if(board[i][j] == 'O')
board[i][j] = 'X';
}
}
};