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); 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 (edgeCount[nodeList.get(i)] != nodeList.size() - 1) { complete = false; break; } } if (complete) { completeComponents++; } }
return completeComponents; } }
|
References
2685. Count the Number of Complete Components