2685. Count the Number of Complete Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
private static class UnionFind {
private final int[] parent;

public UnionFind(int n) {
this.parent = new int[n];
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
}
}

public void union(int x, int y) {
int xRoot = getRoot(x), yRoot = getRoot(y);
if (xRoot == yRoot) {
return;
}

parent[xRoot] = yRoot;
}

private int getRoot(int x) {
if (x != parent[x]) {
int p = parent[x];
parent[x] = getRoot(p);
}

return parent[x];
}

public Map<Integer, List<Integer>> getComponents() {
Map<Integer, List<Integer>> componentMap = new HashMap<>();
for (int i = 0; i < parent.length; i++) {
int node = i, root = getRoot(i); // 注意此处必须使用 getRoot(i) 而不能使用 parent[i], 比如 6 -> 8, 5 -> 6 两条边进行 union 操作后 5 依然指向 6 而不是 8
componentMap.computeIfAbsent(root, key -> new ArrayList<>()).add(node);
}
return componentMap;
}
}

public int countCompleteComponents(int n, int[][] edges) {
int completeComponents = 0;

UnionFind unionFind = new UnionFind(n);
int[] edgeCount = new int[n]; // 每个节点上边的数量
for (int[] edge : edges) {
unionFind.union(edge[0], edge[1]);
edgeCount[edge[0]]++;
edgeCount[edge[1]]++;
}

Map<Integer, List<Integer>> componentMap = unionFind.getComponents();
for (List<Integer> nodeList : componentMap.values()) {
boolean complete = true;
for (int i = 0; i < nodeList.size(); i++) {
// 注意题目要求任意两个节点中都必须存在路径,则不能简单的判断节点上的边的数量是否相等来确定是否为完全连通分量,比如四个点组成的正方形,就不是完全连通分量,应该使用如下的 if 进行判断
if (edgeCount[nodeList.get(i)] != nodeList.size() - 1) {
complete = false;
break;
}
}
if (complete) {
completeComponents++;
}
}

return completeComponents;
}
}

References

2685. Count the Number of Complete Components