Skip to content

Commit ab27f8d

Browse files
committed
add Number of Connected Components in an Undirected Graph solution
1 parent a74c82a commit ab27f8d

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* [Problem]: [3651] Number of Connected Components in an Undirected Graph
3+
* (https://www.lintcode.com/problem/3651/)
4+
*/
5+
export class Solution {
6+
/**
7+
* @param n: the number of vertices
8+
* @param edges: the edges of undirected graph
9+
* @return: the number of connected components
10+
*/
11+
countComponents(n: number, edges: number[][]): number {
12+
//시간복잡도 O(n + e)
13+
// 공간복잡도 O(n + e)
14+
function dfsFunc(n: number, edges: number[][]): number {
15+
const visited = new Array(n).fill(false);
16+
const graph: number[][] = Array.from({ length: n }, () => []);
17+
18+
for (const [node, adjacent] of edges) {
19+
graph[node].push(adjacent);
20+
graph[adjacent].push(node);
21+
}
22+
23+
function dfs(node: number) {
24+
visited[node] = true;
25+
for (const neighbor of graph[node]) {
26+
if (!visited[neighbor]) {
27+
dfs(neighbor);
28+
}
29+
}
30+
}
31+
32+
let count = 0;
33+
34+
for (let i = 0; i < n; i++) {
35+
if (!visited[i]) {
36+
count++;
37+
dfs(i);
38+
}
39+
}
40+
41+
return count;
42+
}
43+
// 시간복잡도 O(n + e)
44+
// 공간복잡도 O(n + e)
45+
function stackFunc(n: number, edges: number[][]): number {
46+
const visited = new Array(n).fill(false);
47+
const graph: number[][] = Array.from({ length: n }, () => []);
48+
let count = 0;
49+
50+
for (const [node, adjacent] of edges) {
51+
graph[node].push(adjacent);
52+
graph[adjacent].push(node);
53+
}
54+
55+
for (let i = 0; i < n; i++) {
56+
if (visited[i]) continue;
57+
count++;
58+
const stack = [i];
59+
60+
while (stack.length) {
61+
const node = stack.pop()!;
62+
visited[node] = true;
63+
64+
for (let adj of graph[node]) {
65+
if (!visited[adj]) stack.push(adj);
66+
}
67+
}
68+
}
69+
70+
return count;
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)