Surrounded Regions

Given a 2D board containing 'X' and '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,

  1. X X X X
  2. X O O X
  3. X X O X
  4. X O X X

After running your function, the board should be:

  1. X X X X
  2. X X X X
  3. X X X X
  4. X O X X

Solution:

  1. public class Solution {
  2. int[] dx = {-1, 1, 0, 0};
  3. int[] dy = {0, 0, -1, 1};
  4. public void solve(char[][] board) {
  5. if (board == null || board.length == 0 || board[0].length == 0) return;
  6. int n = board.length;
  7. int m = board[0].length;
  8. // scan the borders and mark the 'O's to '1'
  9. for (int i = 0; i < n; i++)
  10. for (int j = 0; j < m; j++)
  11. if ((i == 0 || i == n - 1 || j == 0 || j == m - 1) && board[i][j] == 'O')
  12. bfs(board, n, m, i, j);
  13. // scan the inner area and mark the 'O's to 'X'
  14. for (int i = 1; i < n; i++)
  15. for (int j = 1; j < m; j++)
  16. if (board[i][j] == 'O')
  17. board[i][j] = 'X';
  18. // reset all the '1's to 'O's
  19. for (int i = 0; i < n; i++)
  20. for (int j = 0; j < m; j++)
  21. if (board[i][j] == '1')
  22. board[i][j] = 'O';
  23. }
  24. void bfs(char[][] board, int n, int m, int i, int j) {
  25. Queue<int[]> queue = new LinkedList<int[]>();
  26. queue.add(new int[]{i, j});
  27. board[i][j] = '1';
  28. while (!queue.isEmpty()) {
  29. int[] pos = queue.poll();
  30. for (int k = 0; k < 4; k++) {
  31. i = pos[0] + dx[k];
  32. j = pos[1] + dy[k];
  33. if (i >= 0 && i < n && j >= 0 && j < m && board[i][j] == 'O') {
  34. board[i][j] = '1';
  35. queue.add(new int[]{i, j});
  36. }
  37. }
  38. }
  39. }
  40. }