https://leetcode.com/problems/surrounded-regions/
问题描述
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.
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
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically.
解题思路
对边界节点做深度优先搜索,若某个节点为O,则与其相连的点O都不能改成X,将其标定为1;
然后遍历所有节点,若某点为O,将其改为X ;若某节点为1,将其改为O。
Solution
class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.size()<3)
return;
int rows=board.size();
int cols=board[0].size();
for(int i=0;i<rows;i++)
{
dfs(i,0,board);
dfs(i,cols-1,board);
}
for(int j=0;j<cols;j++)
{
dfs(0,j,board);
dfs(rows-1,j,board);
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++){
if(board[i][j]=='O')board[i][j]='X';
if(board[i][j]=='1')board[i][j]='O';
}
}
}
void dfs(int x,int y,vector<vector<char>>&board)
{
if(x<0||y<0||x>=board.size()||y>=board[0].size()||board[x][y]!='O')
return ;
board[x][y]='1';
dfs(x+1,y,board);
dfs(x-1,y,board);
dfs(x,y+1,board);
dfs(x,y-1,board);
return ;
}
};