Skip to content

Commit e110a5b

Browse files
authored
[ PS ] : Number of Connected Components in an Undirected Graph
1 parent 2d70f08 commit e110a5b

File tree

1 file changed

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

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
/**
3+
* @param n: the number of vertices
4+
* @param edges: the edges of undirected graph
5+
* @return: the number of connected components
6+
*/
7+
const countComponents = function (n, edges) {
8+
// graph 만들기
9+
const graph = Array.from({ length: n }).map(() => []);
10+
11+
for (const [u, v] of edges) {
12+
graph[u].push(v);
13+
graph[v].push(u);
14+
}
15+
16+
// 각 노드 순회하기
17+
let count = 0;
18+
const visited = new Set();
19+
20+
for (let i = 0; i < n; i++) {
21+
if (visited.has(i)) {
22+
continue;
23+
}
24+
25+
count += 1;
26+
27+
// bfs
28+
const queue = [i];
29+
visited.add(i);
30+
31+
while (queue.length) {
32+
const u = queue.shift();
33+
34+
for (const v of graph[u]) {
35+
if (!visited.has(v)) {
36+
visited.add(v);
37+
queue.push(v);
38+
}
39+
}
40+
}
41+
}
42+
43+
return count;
44+
}
45+
46+
// 시간복잡도: O(E)
47+
// 공간복잡도: O(V)

0 commit comments

Comments
 (0)