Given a 2D board containing ‘X‘ ‘O‘ and, capture all regions surrounded by ‘X‘ .
A region was captured by flipping all ‘O‘ s into ‘X‘ s-surrounded region.
For example,
x x x xx o o xx x o xx o x x
After running your function, the board should is:
x x x xx x x xx x x xx O x x
Idea: Starting with the ' 0 ' on the four side, the ' O ' adjacent to it is not changed, and is recorded as ' D '. Reverse Thinking! Never be changed ' o ' instead of looking for being changed ' o '
classSolution { Public: voidDfsintXinty) { if(x<0|| X>=m | | y<0|| Y>=n | | board[x][y]!='O')return; Board[x][y]='D'; //four-direction traversal of a graphDFS (X-1, y); DFS (x+1, y); DFS (x, y-1); DFS (x, y+1); } voidSolve (vector<vector<Char>> &Board) { if(Board.empty ())return; This->board =Board; M=board.size (); N=board[0].size (); if(n<=2|| m<=2)return; for(intj=0; j<n;j++) {DFS (0, J); DFS (M-1, J); } for(intI=1; i<m;i++) {DFS (I,0); DFS (I,n-1); } for(intI=0; i<m;i++) for(intj=0; j<n;j++){ if( This->board[i][j]=='O') This->board[i][j]='X'; Else if( This->board[i][j]=='D') This->board[i][j]='O'; } Board= This-Board; }Private: intM,n; Vector<vector<Char>>board;};
Surrounded regions (Graph; DFS)