Skip to content

Commit 28d5770

Browse files
committed
feat: 문제풀이 추가
1 parent 6661512 commit 28d5770

File tree

1 file changed

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

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// V는 정점, E는 간선
2+
// 시간 복잡도: O(V + E)
3+
// 공간 복잡도: O(V + E)
4+
5+
class Solution {
6+
/**
7+
* @param {number} n
8+
* @param {number[][]} edges
9+
* @returns {number}
10+
*/
11+
countComponents(n, edges) {
12+
const visited = Array.from({length: n}, () => false);
13+
const graph = new Map();
14+
15+
for (const [v, d] of edges) {
16+
if (!graph.has(v)) graph.set(v, []);
17+
if (!graph.has(d)) graph.set(d, []);
18+
19+
graph.get(v).push(d);
20+
graph.get(d).push(v);
21+
}
22+
23+
const dfs = (node) => {
24+
visited[node] = true
25+
for (let nei of graph.get(node) || []) {
26+
if (!visited[nei]) dfs(nei)
27+
}
28+
}
29+
30+
let count = 0;
31+
for (let i = 0; i < n; i++) {
32+
if (!visited[i]) {
33+
dfs(i);
34+
count++;
35+
}
36+
}
37+
38+
39+
return count
40+
}
41+
}

0 commit comments

Comments
 (0)