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
Solution:
By traversing the points on the four edges to determine if there is an ' O ' on the Edge,
1. If there is no ' o ' on the four side, stating that ' o ' (if any) is surrounded by ' x ', traverse the entire two-dimensional array to change ' o ' directly to ' X '.
2. If ' O ' is found, follow the up and down direction of the ' o ' and determine if it is ' o ', if yes, join the queue.
Public classSolution { Public voidSolveChar[] board) { if(board = =NULL|| Board.length = = 0) return; if(Board[0].length = = 0) return; introw =board.length; intCol = board[0].length; for(inti = 0; i < row; ++i) {BFS (board, I,0); BFS (board, I, Col-1); } for(inti = 1; i < col-1; ++i) {BFS (board,0, i); BFS (board, Row-1, i); } for(inti = 0; i < row; ++i) { for(intj = 0; J < Col; ++j) {if(Board[i][j] = = ' O ') Board[i][j]= ' X '; } } for(inti = 0; i < row; ++i) { for(intj = 0; J < Col; ++j) {if(Board[i][j] = = ' D ') Board[i][j]= ' O '; } } } Private voidBFsChar[] board,intXinty) {if(board[x][y]!= ' O ') return; Board[x][y]= ' D '; Queue<Integer> queue=NewLinkedlist<integer>(); Queue.add (x*board[0].length+y); while(!Queue.isempty ()) { intCode=Queue.poll (); intRow=code/board[0].length; intCol=code%board[0].length; if(row-1>=0&&board[row-1][col]== ' O ') {queue.add (row-1) *board[0].length+col); Board[row-1][col]= ' D '; } if(row+1<board.length&&board[row+1][col]== ' O ') {queue.add (row+1) *board[0].length+col); Board[row+1][col]= ' D '; } if(col-1>=0&&board[row][col-1]== ' O ') {queue.add (row*board[0].length+col-1); Board[row][col-1]= ' D '; } if(col+1<board[0].length&&board[row][col+1]== ' O ') {queue.add (row*board[0].length+col+1); Board[row][col+1]= ' D '; } } }}
[Leetcode] Surrounded regions