Skip to content

Commit b19d3cb

Browse files
solves #323: Number of Connected Components in an Undirected Graph in java
1 parent 54958ec commit b19d3cb

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@
270270
| 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher) | | |
271271
| 320 | 🔒 [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation) | | |
272272
| 322 | [Coin Change](https://leetcode.com/problems/coin-change) | | |
273-
| 323 | 🔒 [Number of Connected Components in Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph) | | |
273+
| 323 | 🔒 [Number of Connected Components in Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph) | [![Java](assets/java.png)](src/NumberOfConnectedComponentsInAnUndirectedGraph.java) | |
274274
| 324 | [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii) | | |
275275
| 325 | 🔒 [Maximum Size Subarray Sum Equals K](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k) | | |
276276
| 326 | [Power of Three](https://leetcode.com/problems/power-of-three) | [![Java](assets/java.png)](src/PowerOfThree.java) [![Python](assets/python.png)](python/power_of_three.py) | |
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph
2+
// T: O(V + E * alpha(V)) alpha = inverse ackerman function
3+
// S: O(V)
4+
5+
public class NumberOfConnectedComponentsInAnUndirectedGraph {
6+
private static final class DisjointSet {
7+
private final int[] root, rank;
8+
9+
public DisjointSet(int size) {
10+
root = new int[size];
11+
rank = new int[size];
12+
for (int i = 0 ; i < size ; i++) {
13+
root[i] = i;
14+
rank[i] = 1;
15+
}
16+
}
17+
18+
public int find(int num) {
19+
if (num == root[num]) {
20+
return num;
21+
}
22+
return root[num] = find(root[num]);
23+
}
24+
25+
public boolean areConnected(int x, int y) {
26+
return find(x) == find(y);
27+
}
28+
29+
public void union(int x, int y) {
30+
final int rootX = find(x), rootY = find(y);
31+
if (rootX == rootY) {
32+
return;
33+
}
34+
if (rank[rootX] < rank[rootY]) {
35+
root[rootX] = rootY;
36+
} else if (rank[rootX] > rank[rootY]) {
37+
root[rootY] = rootX;
38+
} else {
39+
root[rootY] = rootX;
40+
rank[rootX]++;
41+
}
42+
}
43+
}
44+
45+
public int countComponents(int n, int[][] edges) {
46+
final DisjointSet disjointSet = new DisjointSet(n);
47+
for (int[] edge : edges) {
48+
if (!disjointSet.areConnected(edge[0], edge[1])) {
49+
disjointSet.union(edge[0], edge[1]);
50+
n--;
51+
}
52+
}
53+
return n;
54+
}
55+
}

0 commit comments

Comments
 (0)