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

分析

广搜。从上下左右四个边界往里走,凡是能碰到的'O',都是跟边界接壤的,应该保留。

代码

  1. // Surrounded Regions
  2. // BFS,时间复杂度O(n),空间复杂度O(n)
  3. public class Solution {
  4. public void solve(char[][] board) {
  5. if (board.length == 0) return;
  6. final int m = board.length;
  7. final int n = board[0].length;
  8. for (int i = 0; i < n; i++) {
  9. bfs(board, 0, i);
  10. bfs(board, m - 1, i);
  11. }
  12. for (int j = 1; j < m - 1; j++) {
  13. bfs(board, j, 0);
  14. bfs(board, j, n - 1);
  15. }
  16. for (int i = 0; i < m; i++)
  17. for (int j = 0; j < n; j++)
  18. if (board[i][j] == 'O')
  19. board[i][j] = 'X';
  20. else if (board[i][j] == '+')
  21. board[i][j] = 'O';
  22. }
  23. private static void bfs(char[][] board, int i, int j) {
  24. Queue<State> q = new LinkedList<>();
  25. final int m = board.length;
  26. final int n = board[0].length;
  27. final Function<State, Boolean> stateIsValid = (State s) -> {
  28. if (s.x < 0 || s.x >= m || s.y < 0 || s.y >= n ||
  29. board[s.x][s.y] != 'O')
  30. return false;
  31. return true;
  32. };
  33. final Function<State, ArrayList<State>> stateExtend = (State s) -> {
  34. ArrayList<State> result = new ArrayList<>();
  35. final int x = s.x;
  36. final int y = s.y;
  37. // 上下左右
  38. State[] newStates = new State[]{new State(x-1, y),
  39. new State(x+1,y),
  40. new State(x,y-1),
  41. new State(x,y+1)
  42. };
  43. for (int k = 0; k < 4; ++k) {
  44. if (stateIsValid.apply(newStates[k])) {
  45. // 既有标记功能又有去重功能
  46. board[newStates[k].x][newStates[k].y] = '+';
  47. result.add(newStates[k]);
  48. }
  49. }
  50. return result;
  51. };
  52. State start = new State(i, j);
  53. if (stateIsValid.apply(start)) {
  54. board[i][j] = '+';
  55. q.offer(start);
  56. }
  57. while (!q.isEmpty()) {
  58. State cur = q.poll();
  59. ArrayList<State> newStates = stateExtend.apply(cur);
  60. for (State s : newStates) q.offer(s);
  61. }
  62. }
  63. static class State {
  64. private int x;
  65. private int y;
  66. public State(int x, int y) {
  67. this.x = x;
  68. this.y = y;
  69. }
  70. }
  71. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/bfs/surrounded-regions.html