LeetCode130:
给你一个 m x n 的矩阵 board ,由若干字符 ‘X’ 和 ‘O’ ,找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。

思路

把与边界上的’O’相连看作连通,且在并查集里面进行连通;则剩下的就是被’X’封闭的’O’。

  1. class UnionFind {
  2. private int[] father;
  3. private int nums = 0;
  4. public UnionFind(int len) {
  5. father = new int[len];
  6. for (int i = 0; i < len; i++) {
  7. father[i] = i;
  8. }
  9. }
  10. public void add(int i, int j) {
  11. father[i] = j;
  12. }
  13. public void merge(int i, int j) {
  14. int rooti = find(i);
  15. int rootj = find(j);
  16. if (rooti != rootj) {
  17. father[rootj] = rooti;
  18. }
  19. }
  20. public int find(int i) {
  21. int root = i;
  22. while (father[root] != root) {
  23. father[root] = father[father[root]];
  24. root = father[root];
  25. }
  26. return root;
  27. }
  28. public boolean isConnected(int i, int j) {
  29. int rooti = find(i);
  30. int rootj = find(j);
  31. if (rooti == rootj) {
  32. return true;
  33. }
  34. return false;
  35. }
  36. }
  1. class Solution {
  2. public void solve(char[][] board) {
  3. int cols = board[0].length;
  4. int rows = board.length;
  5. UnionFind find = new UnionFind(rows * cols + 1);
  6. int dummynode = rows * cols;
  7. for (int i = 0; i < rows; i++) {
  8. for (int j = 0; j < cols; j++) {
  9. if (board[i][j] == 'O') {
  10. if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1) {
  11. //注意使用merge,而不使用add,是因为add是加入的含义,不是合并
  12. find.merge(encode(i, j, cols), dummynode);
  13. } else {
  14. if (i > 0 && board[i - 1][j] == 'O') {
  15. find.merge(encode(i, j, cols), encode(i - 1, j, cols));
  16. }
  17. if (i + 1 < cols && board[i + 1][j] == 'O') {
  18. find.merge(encode(i, j, cols), encode(i + 1, j, cols));
  19. }
  20. if (j > 0 && board[i][j - 1] == 'O') {
  21. find.merge(encode(i, j, cols), encode(i, j - 1, cols));
  22. }
  23. if (j + 1 < rows && board[i][j + 1] == 'O') {
  24. find.merge(encode(i, j, cols), encode(i, j + 1, cols));
  25. }
  26. }
  27. }
  28. }
  29. }
  30. for (int i = 0; i < rows; i++) {
  31. for (int j = 0; j < cols; j++) {
  32. //不要用find,我们的最终目的是判断是否联系,而不是是否有共同祖先
  33. if (find.isConnected(encode(i, j, cols), dummynode)) {
  34. board[i][j] = '0';
  35. } else {
  36. board[i][j] = 'X';
  37. }
  38. }
  39. }
  40. }
  41. public int encode(int i, int j, int cols) {
  42. return i * cols + j;
  43. }
  44. }