Skip to content

Commit dfff6ef

Browse files
committed
number of connected components in an undirected graph solution
1 parent df9f1ed commit dfff6ef

File tree

1 file changed

+36
-0
lines changed
  • number-of-connected-components-in-an-undirected-graph

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
export class Solution {
2+
/**
3+
* @param n: the number of vertices
4+
* @param edges: the edges of undirected graph
5+
* @return: the number of connected components
6+
*/
7+
countComponents(n: number, edges: number[][]): number {
8+
const parent = Array.from({ length: n }, (_, i) => i);
9+
let components = n;
10+
11+
const find = (i: number): number => {
12+
if (parent[i] === i) {
13+
return i;
14+
}
15+
16+
parent[i] = find(parent[i]);
17+
return parent[i];
18+
};
19+
20+
const union = (a: number, b: number): void => {
21+
const rootA = find(a);
22+
const rootB = find(b);
23+
24+
if (rootA !== rootB) {
25+
parent[rootA] = rootB;
26+
components--;
27+
}
28+
};
29+
30+
for (const [a, b] of edges) {
31+
union(a, b);
32+
}
33+
34+
return components;
35+
}
36+
}

0 commit comments

Comments
 (0)