Surrounded Regions
Description:
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
Code:
1 struct vertex 2 { 3 int row; 4 int col; 5 vertex (int x, int y):row(x),col(y) 6 { 7 8 } 9 }; 10 11 void BFSTraverse (vector< vector<char> >& board, int i, int j) 12 {//因为值被修改为'S'就说明该元素已被访问,所以本题中可以不用另外的变量记录访问状态 13 board[i][j] = 'S'; 14 deque<vertex>m; 15 m.push_back( vertex(i,j) ); 16 while ( !m.empty() ) 17 { 18 vertex v = m.front(); 19 m.pop_front(); 20 21 int mRow = v.row-1; 22 if ( mRow >=0 && board[mRow][v.col] == 'O') 23 {//上面的元素 24 board[mRow][v.col] = 'S'; 25 m.push_back( vertex(mRow, v.col) ); 26 } 27 mRow = v.row+1; 28 if ( mRow < board.size() && board[mRow][v.col] == 'O') 29 {//下面的元素 30 board[mRow][v.col] = 'S'; 31 m.push_back( vertex(mRow, v.col) ); 32 } 33 int mCol = v.col - 1; 34 if ( mCol >=0 && board[v.row][mCol] == 'O') 35 {//左面的元素 36 board[v.row][mCol] = 'S'; 37 m.push_back( vertex(v.row, mCol)); 38 } 39 mCol = v.col + 1; 40 if ( mCol < board[0].size() && board[v.row][mCol] == 'O' ) 41 {//右面的元素 42 board[v.row][mCol] = 'S'; 43 m.push_back( vertex(v.row, mCol)); 44 } 45 } 46 } 47 48 void solve(vector< vector<char> >& board) 49 { 50 int row = board.size(); 51 if ( row!=0 ) 52 { 53 int col = board[0].size(); 54 for (int j = 0; j < col; ++j) 55 { 56 if ( board[0][j] == 'O') 57 BFSTraverse (board, 0, j); 58 if ( board[row-1][j] == 'O') 59 BFSTraverse (board, row-1, j); 60 } 61 for (int i = 1; i < row-1; ++i) 62 { 63 if ( board[i][0] == 'O') 64 BFSTraverse (board, i, 0); 65 if ( board[i][col-1] == 'O' ) 66 BFSTraverse (board, i, col-1); 67 } 68 69 for (int i = 0; i < row; ++i ) 70 { 71 for ( int j = 0; j < col; ++j ) 72 { 73 if (board[i][j] == 'S') 74 board[i][j] = 'O'; 75 else if (board[i][j] == 'O') 76 board[i][j] = 'X'; 77 else 78 ; 79 } 80 }//for 81 }//if 82 }