Given a 2D board containing 'X'
and 'O'
(the letter 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
package leetCode; import java.util.LinkedList; import java.util.Queue; /** * Created by lxw, liwei4939@126.com on 2018/3/26. */ class Point{ int x; int y; public Point(int x, int y){ this.x = x; this.y = y; } } public class L130_SurroundedRegions { public void solve(char[][] board){ if (board.length == 0){ return; } int row = board.length; int col = board[0].length; Queue<Point> queue = new LinkedList<>(); for (int r = 0; r < row; r++){ if (board[r][0] == 'O'){ board[r][0] = '+'; queue.add(new Point(r, 0)); } if (board[r][col -1] == 'O'){ board[r][col-1] = '+'; queue.add(new Point(r, col-1)); } } for (int c= 0; c < col; c++){ if (board[0][c] == 'O'){ board[0][c] = '+'; queue.add(new Point(0, c)); } if (board[row-1][c] == 'O'){ board[row-1][c] = '+'; queue.add(new Point(row-1, c)); } } while (!queue.isEmpty()){ Point p = queue.poll(); int r = p.x; int c = p.y; if (r-1 >= 0 && board[r-1][c] == 'O'){ board[r-1][c] = '+'; queue.add(new Point(r-1, c)); } if (r+1 < row && board[r+1][c] == 'O'){ board[r+1][c] ='+'; queue.add(new Point(r+1, c)); } if (c-1 >= 0 && board[r][c-1] == 'O'){ board[r][c-1] = '+'; queue.add(new Point(r, c-1)); } if (c+1 < col && board[r][c+1] == 'O'){ board[r][c+1] = '+'; queue.add(new Point(r,c+1)); } } for (int i = 0; i<row; i++){ for (int j=0; j<col; j++){ if (board[i][j] == 'O') board[i][j] = 'X'; if (board[i][j] == '+') board[i][j] = 'O'; } } } }