Skip to content

Commit 70ef94c

Browse files
committed
Feat: 323. Number of Connected Components in an Undirected Graph
1 parent e808b1a commit 70ef94c

File tree

1 file changed

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

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph
3+
* T.C. O(V + E)
4+
* S.C. O(V + E)
5+
*/
6+
function countComponents(n: number, edges: number[][]): number {
7+
const graph = new Map<number, number[]>();
8+
9+
for (let i = 0; i < n; i++) {
10+
graph.set(i, []);
11+
}
12+
13+
for (const [u, v] of edges) {
14+
graph.get(u)!.push(v);
15+
graph.get(v)!.push(u);
16+
}
17+
18+
function dfs(node: number) {
19+
visited.add(node);
20+
21+
for (const neighbor of graph.get(node)!) {
22+
if (!visited.has(neighbor)) {
23+
dfs(neighbor);
24+
}
25+
}
26+
}
27+
28+
const visited = new Set<number>();
29+
30+
let components = 0;
31+
32+
for (let i = 0; i < n; i++) {
33+
if (!visited.has(i)) {
34+
components++;
35+
dfs(i);
36+
}
37+
}
38+
39+
return components;
40+
}
41+
42+
/**
43+
* Using Union Find
44+
* T.C. O(V + E)
45+
*
46+
*/
47+
function countComponents(n: number, edges: number[][]): number {
48+
const parent = Array.from({ length: n }, (_, i) => i);
49+
50+
// find and compress path
51+
function find(x: number): number {
52+
if (parent[x] !== x) {
53+
parent[x] = find(parent[x]);
54+
}
55+
return parent[x];
56+
}
57+
58+
// union two sets and check if they have the same root
59+
function union(x: number, y: number): boolean {
60+
const rootX = find(x);
61+
const rootY = find(y);
62+
parent[rootX] = rootY;
63+
return true;
64+
}
65+
66+
for (const [x, y] of edges) {
67+
union(x, y);
68+
}
69+
70+
return new Set(parent.map(find)).size;
71+
}

0 commit comments

Comments
 (0)