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
Subscribe to see which companies asked this question
核心思想:只有边界上'O'的位置组成的片区不会被'X'包围。
因此先对边界上的'O'遍历之后暂存为'*'。
非'*'的'O'即被'X'包围了
struct POS
{int x;
int y;
POS(int newx,int newy):x(newx),y(newy) {}
};
class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.empty()||board[0].empty())
return;
int m = board.size();
int n = board[0].size();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j]=='O')
{
if(i==0||i==m-1||j==0||j==n-1)
{
dfs(board,i,j,m,n);
}
}
}
}
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 dfs(vector<vector<char>> &board, int i, int j, int m, int n)
{
stack<POS *> s;
POS * pos = new POS(i,j);
s.push(pos);
board[i][j]='*';
while(!s.empty())
{
POS *top=s.top();
if(top->x>0&&board[top->x-1][top->y]=='O')
{
POS *up=new POS(top->x-1,top->y);
s.push(up);
board[up->x][up->y]='*';
continue;
}
if(top->x<m-1&&board[top->x+1][top->y]=='O')
{
POS *down=new POS(top->x+1,top->y);
s.push(down);
board[down->x][down->y]='*';
continue;
}
if(top->y>0&&board[top->x][top->y-1]=='O')
{
POS *left=new POS(top->x,top->y-1);
s.push(left);
board[left->x][left->y]='*';
continue;
}
if(top->y<n-1&&board[top->x][top->y+1]=='O')
{
POS *right=new POS(top->x,top->y+1);
s.push(right);
board[right->x][right->y]='*';
continue;
}
s.pop();
}
}
};