class Solution {
public int regionsBySlashes(String[] grid) {
int N = grid.length;
DSU dsu = new DSU(4 * N * N); //这是自己定义的并查集的类,可以先看下这个类。
//创建类,类里面有一个4 * N * N的并查集数组
for (int r = 0; r < N; ++r) //row代表行
for (int c = 0; c < N; ++c) { //col代表列 两个for遍历grid的每个字符
int root = 4 * (r * N + c);
char val = grid[r].charAt(c); //字符
if (val != '\\') { //如果为 ’/‘或者’ ‘则组合(0,1),(2,3).
dsu.union(root + 0, root + 1);
dsu.union(root + 2, root + 3);
}
if (val != '/') { //如果为 ’\\‘或者’ ‘则组合(0,2),(1,3)
dsu.union(root + 0, root + 2);
dsu.union(root + 1, root + 3);
}
if (r + 1 < N) // 如果不是最后一行,则向下归并 :3 归并下行的0 0 0
dsu.union(root + 3, (root + 4 * N) + 0); // 1 2 1 2
if (r - 1 >= 0) //如果不是第一行,则向上归并:0归并上行的3 3 3
dsu.union(root + 0, (root - 4 * N) + 3); // 0 0
// 1 2 1 2
if (c + 1 < N)//如果不是最后一列,则向右归并:2归并右邻的1 3 3
dsu.union(root + 2, (root + 4) + 1);
if (c - 1 >= 0)//如果不是第一列,则向左归并:1归并左邻的2
dsu.union(root + 1, (root - 4) + 2);
}
int ans = 0;
for (int x = 0; x < 4 * N * N; ++x) { //最后在使每个点的值为最高级主人,再计数一共有几个主人。就得出结果
if (dsu.find(x) == x)
ans++;
}
return ans;
}
}
class DSU { //并查集的类
int[] parent;
public DSU(int N) {
parent = new int[N];//创建并查集数组,每个下标的值是自己(自己是自己的主人)。
for (int i = 0; i < N; ++i)
parent[i] = i;
}
public int find(int x) {//查找自己的主人,并更新自己的值为最高级的主人。
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
public void union(int x, int y) {//归并。x的主人归并y的主人。
parent[find(x)] = find(y);
}
}
作者:dogrong
链接:https://leetcode.cn/problems/regions-cut-by-slashes/solution/guan-yu-guan-fang-bing-cha-ji-ti-jie-de-zi-wo-li-j/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
不会写,CV一下,以后学习