Skip to content

Commit e085714

Browse files
authored
Update Number of Connected Components in an Undirected Graph.java
1 parent b265e9d commit e085714

File tree

1 file changed

+25
-47
lines changed

1 file changed

+25
-47
lines changed
Lines changed: 25 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,29 @@
11
class Solution {
2-
public int countComponents(int n, int[][] edges) {
3-
DisjointSet disjointSet = new DisjointSet(n);
4-
for (int[] edge : edges) {
5-
disjointSet.union(edge[0], edge[1]);
6-
}
7-
Set<Integer> rootSet = new HashSet<>();
8-
for (int i = 0; i < n; i++) {
9-
rootSet.add(disjointSet.find(i));
10-
}
11-
return rootSet.size();
12-
}
13-
14-
private static class DisjointSet {
15-
16-
private final int[] root;
17-
private final int[] rank;
18-
19-
public DisjointSet(int size) {
20-
this.root = new int[size];
21-
this.rank = new int[size];
22-
for (int i = 0; i < size; i++) {
23-
this.root[i] = i;
24-
this.rank[i] = 1;
25-
}
26-
}
27-
28-
public void union(int nodeOne, int nodeTwo) {
29-
int rootOne = find(nodeOne);
30-
int rootTwo = find(nodeTwo);
31-
if (rootOne != rootTwo) {
32-
if (this.rank[rootOne] > this.rank[rootTwo]) {
33-
this.root[rootTwo] = rootOne;
34-
} else if (this.rank[rootOne] < this.rank[rootTwo]) {
35-
this.root[rootOne] = rootTwo;
36-
} else {
37-
this.root[rootTwo] = rootOne;
38-
this.rank[rootOne]++;
2+
public int countComponents(int n, int[][] edges) {
3+
Map<Integer, Set<Integer>> graph = new HashMap<>();
4+
for (int[] edge : edges) {
5+
graph.computeIfAbsent(edge[0], k -> new HashSet<>()).add(edge[1]);
6+
graph.computeIfAbsent(edge[1], k -> new HashSet<>()).add(edge[0]);
397
}
40-
}
41-
}
42-
43-
44-
public int find(int node) {
45-
if (node == root[node]) {
46-
return node;
47-
}
48-
return root[node] = find(root[node]);
8+
int connectedComponentCount = 0;
9+
Set<Integer> visited = new HashSet<>();
10+
for (int i = 0; i < n; i++) {
11+
if (!visited.contains(i)) {
12+
Queue<Integer> queue = new LinkedList<>();
13+
visited.add(i);
14+
queue.add(i);
15+
while (!queue.isEmpty()) {
16+
int removed = queue.remove();
17+
for (Integer neighbor : graph.getOrDefault(removed, new HashSet<>())) {
18+
if (!visited.contains(neighbor)) {
19+
queue.add(neighbor);
20+
visited.add(neighbor);
21+
}
22+
}
23+
}
24+
connectedComponentCount++;
25+
}
26+
}
27+
return connectedComponentCount;
4928
}
50-
}
5129
}

0 commit comments

Comments
 (0)