Problem
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.
Example:
X X X XX O O XX X O XX O X XAfter running your function, the board should be:
X X X XX X X XX X X XX O X XExplanation:
Surrounded regions shouldn’t be on the border, which means that any ‘O’ on the border of the board are not flipped to ‘X’. Any ‘O’ that is not on the border and it is not connected to an ‘O’ on the border will be flipped to ‘X’. Two cells are connected if they are adjacent cells connected horizontally or vertically.
Solution
class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) return;
int m = board.length, n = board[0].length;
int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
boolean[][] visited = new boolean[m][n]; //optional
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 || i == m-1 || j == 0 || j == n-1) && board[i][j] == ‘O’ && !visited[i][j]) {
Queue<int[]> queue = new LinkedList<>();
board[i][j] = ‘B’;
//visited[i][j] = true;
queue.offer(new int[]{i, j});
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int k = 0; k < 4; k++) {
int x = cur[0] + dirs[k][0];
int y = cur[1] + dirs[k][1];
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != ‘O’ || visited[x][y]) continue;
board[x][y] = ‘B’;
//visited[x][y] = true;
queue.offer(new int[]{x, y});
}
}
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == ‘O’) board[i][j] = ‘X’;
else if (board[i][j] == ‘B’) board[i][j] = ‘O’;
}
}
}
}