Skip to content

Commit fa5da0f

Browse files
committed
number of connected components in an undirected graph soluition
1 parent e453381 commit fa5da0f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time Complexity: O(n + e) โ€” ๋…ธ๋“œ n๊ฐœ์™€ ๊ฐ„์„  e๊ฐœ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ์ˆœํšŒ
2+
// Space Complexity: O(n + e) โ€” ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ์ €์žฅ O(n+e), ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ ์ตœ์•… O(n)
3+
function countComponents(n, edges) {
4+
// ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
5+
const adj = Array.from({ length: n }, () => []);
6+
for (const [u, v] of edges) {
7+
adj[u].push(v);
8+
adj[v].push(u);
9+
}
10+
11+
const visited = Array(n).fill(false);
12+
let count = 0;
13+
14+
function dfs(u) {
15+
visited[u] = true;
16+
for (const v of adj[u]) {
17+
if (!visited[v]) dfs(v);
18+
}
19+
}
20+
21+
// ๋ชจ๋“  ๋…ธ๋“œ ์ˆœํšŒ
22+
for (let i = 0; i < n; i++) {
23+
if (!visited[i]) {
24+
count++;
25+
dfs(i);
26+
}
27+
}
28+
29+
return count;
30+
}

0 commit comments

Comments
ย (0)