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 -1 >= 0 ) BFS(board, i-1, j ); if( i + 1 < rows ) BFS(board, i+1, j ); if( j -1 >= 0 ) BFS(board, i, j-1 ); if( j +1 < columns ) BFS(board, i, j+1 ); } void solve(vector<vector<char>> &board) { // Start typing your C/C++ solution below // DO NOT write int main() function rows = board.size(); if( rows == 0) return ; columns = board[0].size(); if(columns == 0) return ; for( int i = 1; i < columns - 1 ; i++) { BFS(board, 0,i);//up BFS(board, rows - 1 , i );//down } for( int i = 0; i< rows; i++) { BFS(board, i, 0 ); //left BFS(board, i, columns - 1); //right } for(int i = 0; i< rows; i++) for(int j = 0; 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; };