Given a 2D board containing ' x ' and ' O ', capture all regions surrounded by ' x '.
A region was captured by flipping all ' O ' s into the ' X ' s in this 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 is:
x x x x
x x x x
x x x x
x O x X
Problem Solving Ideas:
To the outermost lap of the BFS, replace the most connected area of the outer ring, the rest of the ' O ' are surrounded, you can kill directly, Java implementation is as follows:
static public void Solve (char[][] board) {if (board.length <= 2 | | board[0].length <= 2) return;for (int row = 0; row < Board.length; row++) {if (board[row][0] = = ' O ') {board[row][0] = ' T '; BFS (board, Row * board[0].length);} if (board[row][board[0].length-1] = = ' O ') {board[row][board[0].length-1] = ' T '; BFS (board, Row * board[0].length + boar d[0].length-1);}} for (int col = 1; col < board[0].length-1; col++) {if (board[0][col] = = ' O ') {Board[0][col] = ' T '; BFS (board, COL);} if (board[board.length-1][col] = = ' O ') {Board[board.length-1][col] = ' T '; BFS (board, (board.length-1) * Board[0].leng th + col);}} for (int row = 0, row < board.length; row++) for (int col = 0; col < board[0].length; col++) {if (board[row][col] = = ' T ') board[row][col] = ' O '; else if (board[row][col] = = ' O ') board[row][col] = ' X ';}} static public void BFs (char[][] board, int num) {queue<integer> Queue = new linkedlist<integer> (); Queue.add (n UM); while (!queue.isempty ()) {num=queue.poll (); INT row = num/board[0].length;int col = num-row * board[0].length;if (row-1 >= 0 && board[row-1][col] = = ' O ') {Board[row-1][col] = ' T '; Queue.add (num-board[0].length);} if (row + 1 <= board.length-1 && board[row + 1][col] = = ' O ') {board[row + 1][col] = ' T '; Queue.add (num + board [0].length);} if (col-1 >= 0 && board[row][col-1] = = ' O ') {board[row][col-1] = ' T '; Queue.add (num-1);} if (col + 1 <= board[0].length-1 && board[row][col + 1] = = ' O ') {board[row][col + 1] = ' T '; Queue.add (num + 1) ;}}}
Java for Leetcode surrounded regions