Skip to content

Commit 79fab17

Browse files
authored
Create Count the Number of Complete Components.java
1 parent f70a266 commit 79fab17

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public int countCompleteComponents(int n, int[][] edges) {
3+
Map<Integer, Set<Integer>> graph = new HashMap<>();
4+
for (int[] edge : edges) {
5+
int nodeOne = edge[0];
6+
int nodeTwo = edge[1];
7+
graph.computeIfAbsent(nodeOne, k -> new HashSet<>()).add(nodeTwo);
8+
graph.computeIfAbsent(nodeTwo, k -> new HashSet<>()).add(nodeOne);
9+
}
10+
int count = 0;
11+
Set<Integer> visited = new HashSet<>();
12+
for (int i = 0; i < n; i++) {
13+
if (visited.add(i)) {
14+
int[] componentInfo = new int[2];
15+
dfs(i, graph, visited, componentInfo);
16+
if (componentInfo[0] * (componentInfo[0] - 1) == componentInfo[1]) {
17+
count++;
18+
}
19+
}
20+
}
21+
return count;
22+
}
23+
24+
private void dfs(
25+
int node,
26+
Map<Integer, Set<Integer>> graph,
27+
Set<Integer> visited,
28+
int[] componentInfo) {
29+
componentInfo[0]++;
30+
Set<Integer> connections = graph.getOrDefault(node, new HashSet<>());
31+
componentInfo[1] += connections.size();
32+
for (Integer conn : connections) {
33+
if (visited.add(conn)) {
34+
dfs(conn, graph, visited, componentInfo);
35+
}
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)