Skip to content

Commit c31889e

Browse files
committed
Added countComponents solution
1 parent 2c1e8b5 commit c31889e

File tree

1 file changed

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

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
export class Solution {
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+
countComponents(n, edges) {
8+
// write your code here
9+
const graph = Array.from({ length: n }, () => []);
10+
11+
for (const [node, neighbor] of edges) {
12+
graph[node].push(neighbor);
13+
graph[neighbor].push(node);
14+
}
15+
16+
let visited = new Set();
17+
let count = 0;
18+
19+
const dfs = (node) => {
20+
visited.add(node);
21+
for (const nei of graph[node]) {
22+
if (!visited.has(nei)) dfs(nei);
23+
}
24+
};
25+
26+
for (let node = 0; node < n; node++) {
27+
if (!visited.has(node)) {
28+
count++;
29+
dfs(node);
30+
}
31+
}
32+
return count;
33+
}
34+
}
35+
36+
// n: number of node | e: number of edge
37+
// TC: O(n+e)
38+
// SC: O(n+e)

0 commit comments

Comments
 (0)