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,并深度遍历与其邻接的点O,将其都设为一个*标志;
然后将所有的O设为X,最后将设为*标志的恢复成X。
class Solution {
public:
void solve(vector<vector<char>> &board) {
int row = board.size();
int col = board[0].size();
if(row <= 2 || col <= 2) return;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if((board[i][j] == 'O' && i == 0) || (board[i][j] == 'O' && i == row - 1))
dfs(board, i, j);
else if((board[i][j] == 'O' && j == 0) || (board[i][j] == 'O' && j == col - 1))
dfs(board, i, j);
}
}
getResult(board);
}
private:
void dfs(vector<vector<char>> &board, int Row, int Col){
if(board[Row][Col] == 'O'){
board[Row][Col] = '*';
if(Row - 1 >= 0)
dfs(board, Row - 1, Col);
if(Row + 1 <= board.size()-1)
dfs(board, Row + 1, Col);
if(Col - 1 >= 0)
dfs(board, Row, Col - 1);
if(Col + 1 < board[0].size())
dfs(board, Row, Col + 1);
}
else
return;
}
void getResult(vector<vector<char>> &board){
for(int row = 0; row < board.size(); row++)
for(int col = 0; col < board[0].size(); col++){
if(board[row][col] == '*')
board[row][col] = 'O';
else if(board[row][col] == 'O')
board[row][col] = 'X';
}
}
};