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题意:O周围都换成x,这个题目的关注点是在四条边的0是不能替换的。思路:DFS深度优先:从外围是‘0’的开始深度往里走,这时候里面的'0'就有两种命运,一种是跟外围的'0'是联通的,那么这些‘0’就可以存活,剩下的孤立的‘0’就没办法了,就只能被‘X’[cpp] view plain copy
class Solution
{
public:
void dfs(int row, int col, vector<vector<char>>& board)
{
if (row<0 || row>=rows || col<0 || col>=cols)
{
return;
}
if (board[row][col]!='O')
{
return;
}
board[row][col] = '+';
dfs(row - 1, col, board); //up
dfs(row, col + 1, board); //right
dfs(row + 1, col, board); //down
dfs(row, col - 1, board); //left
}
void solve(vector<vector<char>>& board)
{
if (board.size()==0 || board[0].size()==0)
{
return;
}
rows = board.size();
cols = board.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';
}
else if (board[i][j]=='+')
{
board[i][j] = 'O';
}
}
}
}
private:
int rows;//总行号
int cols;//总列号
};