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
The basic idea is that if you label all o that should not be X, then the remaining o is the X.
So, from the O on each side of the matrix to start the graph traversal, into the stack/queue when the corresponding node value from ' O ' into other symbols (I use ' + '), out of the stack/queue of nodes adjacent to the node "O" node to discuss.
When all is done, turn ' o ' into ' X ' and ' + ' to ' o '.
Code:
1 Public classPair {2 intx;3 inty;4Pair (intXinty) {5 This. x =x;6 This. y =y;7 }8 }9 Public voidSolveChar[] board) {Ten intm=board.length; One if(m<=2) A return; - intN=board[0].length; - for(inti=0;i<m;i++) { the if(board[i][0]== ' O ') -DFS (board, I, 0); - if(board[i][n-1]== ' O ') -DFS (board, I, n-1); + } - for(inti=0;i<n;i++) { + if(board[0][i]== ' O ') ADFS (board, 0, i); at if(board[m-1][i]== ' O ') -DFS (board, m-1, i); - } - for(inti=0;i<m;i++) - for(intj=0;j<n;j++) { - if(board[i][j]== ' O ') inboard[i][j]= ' X '; - Else if(board[i][j]== ' + ') toboard[i][j]= ' O '; + } - } the Public voidDfsChar[] BD,intIintj) * { $Stack<pair> st =NewStack<pair>();Panax NotoginsengBD[I][J] = ' + '; -St.push (NewPair (i,j)); the + while(!St.isempty ()) { APair temp =St.pop (); the if(temp.x>0 && bd[temp.x-1][temp.y]== ' O ') { +bd[temp.x-1][temp.y]= ' + '; -St.push (NewPair (temp.x-1, temp.y)); $ } $ if(temp.y<bd[0].length-1 && bd[temp.x][temp.y+1]== ' O ') { -bd[temp.x][temp.y+1]= ' + '; -St.push (NewPair (temp.x, temp.y+1)); the } - if(temp.x<bd.length-1 && bd[temp.x+1][temp.y]== ' O ') {Wuyibd[temp.x+1][temp.y]= ' + '; theSt.push (NewPair (temp.x+1, temp.y)); - } Wu if(temp.y>0 && bd[temp.x][temp.y-1]== ' O ') { -bd[temp.x][temp.y-1]= ' + '; AboutSt.push (NewPair (temp.x, temp.y-1)); $ } - } -}
[Leetcode] [JAVA] Surrounded regions