LeetCode130:
给你一个 m x n 的矩阵 board ,由若干字符 ‘X’ 和 ‘O’ ,找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。
思路
把与边界上的’O’相连看作连通,且在并查集里面进行连通;则剩下的就是被’X’封闭的’O’。
class UnionFind {private int[] father;private int nums = 0;public UnionFind(int len) {father = new int[len];for (int i = 0; i < len; i++) {father[i] = i;}}public void add(int i, int j) {father[i] = j;}public void merge(int i, int j) {int rooti = find(i);int rootj = find(j);if (rooti != rootj) {father[rootj] = rooti;}}public int find(int i) {int root = i;while (father[root] != root) {father[root] = father[father[root]];root = father[root];}return root;}public boolean isConnected(int i, int j) {int rooti = find(i);int rootj = find(j);if (rooti == rootj) {return true;}return false;}}
class Solution {public void solve(char[][] board) {int cols = board[0].length;int rows = board.length;UnionFind find = new UnionFind(rows * cols + 1);int dummynode = rows * cols;for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {if (board[i][j] == 'O') {if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1) {//注意使用merge,而不使用add,是因为add是加入的含义,不是合并find.merge(encode(i, j, cols), dummynode);} else {if (i > 0 && board[i - 1][j] == 'O') {find.merge(encode(i, j, cols), encode(i - 1, j, cols));}if (i + 1 < cols && board[i + 1][j] == 'O') {find.merge(encode(i, j, cols), encode(i + 1, j, cols));}if (j > 0 && board[i][j - 1] == 'O') {find.merge(encode(i, j, cols), encode(i, j - 1, cols));}if (j + 1 < rows && board[i][j + 1] == 'O') {find.merge(encode(i, j, cols), encode(i, j + 1, cols));}}}}}for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {//不要用find,我们的最终目的是判断是否联系,而不是是否有共同祖先if (find.isConnected(encode(i, j, cols), dummynode)) {board[i][j] = '0';} else {board[i][j] = 'X';}}}}public int encode(int i, int j, int cols) {return i * cols + j;}}
