Skip to content

Commit f7a9d09

Browse files
committed
number-of-connected-components-in-an-undirected-graph solution (ts)
1 parent 73e01ba commit f7a9d09

File tree

1 file changed

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

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* TC: O(N + E), N: 노드의 개수, E: 간선의 개수
3+
* SC: O(N + E)
4+
*/
5+
6+
// DFS
7+
function countComponentsDFS(n: number, edges: number[][]): number {
8+
const graph: number[][] = Array.from({ length: n }, () => []);
9+
10+
// 그래프 초기화
11+
for (const [u, v] of edges) {
12+
graph[u].push(v);
13+
graph[v].push(u);
14+
}
15+
16+
const visited = new Set<number>();
17+
18+
function dfs(node: number) {
19+
visited.add(node);
20+
for (const neighbor of graph[node]) {
21+
if (!visited.has(neighbor)) {
22+
dfs(neighbor);
23+
}
24+
}
25+
}
26+
27+
let components = 0;
28+
for (let i = 0; i < n; i++) {
29+
if (!visited.has(i)) {
30+
components++;
31+
dfs(i);
32+
}
33+
}
34+
35+
return components;
36+
}
37+
38+
// BFS
39+
function countComponentsBFS(n: number, edges: number[][]): number {
40+
const graph: number[][] = Array.from({ length: n }, () => []);
41+
42+
// 그래프 초기화
43+
for (const [u, v] of edges) {
44+
graph[u].push(v);
45+
graph[v].push(u);
46+
}
47+
48+
const visited = new Set<number>();
49+
let components = 0;
50+
51+
for (let i = 0; i < n; i++) {
52+
if (!visited.has(i)) {
53+
components++;
54+
const queue: number[] = [i];
55+
56+
while (queue.length > 0) {
57+
const node = queue.shift();
58+
if (node === undefined) continue;
59+
if (visited.has(node)) continue;
60+
visited.add(node);
61+
62+
for (const neighbor of graph[node]) {
63+
if (!visited.has(neighbor)) queue.push(neighbor);
64+
}
65+
}
66+
}
67+
}
68+
69+
return components;
70+
}

0 commit comments

Comments
 (0)