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
solution: 思想是mark 出所有外围的O,里面的不管。
- First scan the four edges of the board, if you meet an 'O', call a recursive mark function to mark that region to something else (for example, '+');
- scan all the board, if you meet an 'O', flip it to 'X';
- scan again the board, if you meet an '+', flip it to 'O';
class Solution {
public:
void BFS(vector<vector<char>> &board, int i , int j){ if(board[i][j] == 'X' || board[i][j] == '#') return;
board[i][j] = '#'; if( i - >= ) BFS(board, i-, j );
if( i + < rows ) BFS(board, i+, j );
if( j - >= ) BFS(board, i, j- );
if( j + < columns ) BFS(board, i, j+ );
}
void solve(vector<vector<char>> &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
rows = board.size();
if( rows == ) return ;
columns = board[].size();
if(columns == ) return ; for( int i = ; i < columns - ; i++)
{
BFS(board, ,i);//up
BFS(board, rows - , i );//down
}
for( int i = ; i< rows; i++)
{
BFS(board, i, ); //left
BFS(board, i, columns - ); //right
}
for(int i = ; i< rows; i++)
for(int j = ; j < columns ; j++)
{
if(board[i][j] == '#')
board[i][j] = 'O';
else if (board[i][j] == 'O')
board[i][j] = 'X';
}
}
private :
int rows;
int columns;
};