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 X1:注意特殊情况;2:将board四边上的0, 以及与这些‘0’相邻的‘0’都设置为‘C';2:把board中的其他的‘0’(这些‘0’全部被‘X'包围)设置为‘X'; 3:把board中的‘C'全部设置为‘0’
void solve(vector<vector<char>> &board) {
if(board.size() == 0 || board.size() == 1 || board[0].size() == 1 || board.size() == 2 || board[0].size() == 2)
return;
int rows = (int)board.size();
int columns = (int)board[0].size();
for(int i = 0; i < columns; i++)
{
if(board[0][i] == 'O')
findUnchangedO(board, 0, i);
}
for(int i = 0; i < rows; i++)
{
if(board[i][0] == 'O')
findUnchangedO(board, i, 0);
}
for(int i = 0; i < columns; i++)
{
if(board[rows-1][i] == 'O')
findUnchangedO(board, rows-1, i);
}
for(int i = 0; i < rows; i++)
{
if(board[i][columns-1] == 'O')
findUnchangedO(board, i, columns-1);
}
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
if(board[i][j] == 'O')
board[i][j] = 'X';
}
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
if(board[i][j] == 'C')
board[i][j] = 'O';
}
return ;
}
void findUnchangedO(vector<vector<char> > &board, int curX, int curY)
{
board[curX][curY] = 'C';
if(curX-1 > 0 && board[curX-1][curY] == 'O')
findUnchangedO(board, curX-1, curY);
if(curY - 1 > 0 && board[curX][curY - 1] == 'O')
findUnchangedO(board, curX, curY - 1);
if(curX + 1 < board.size() && board[curX + 1][curY] == 'O')
findUnchangedO(board, curX + 1, curY);
if(curY + 1 < board[0].size() && board[curX][curY + 1] == 'O')
findUnchangedO(board, curX, curY + 1);
}