Skip to content

Commit f9cb77c

Browse files
authored
Merge pull request neetcode-gh#377 from anthonysim/asim/connectedComponents
323 js countComponents
2 parents 708ba00 + e91f8a8 commit f9cb77c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

javascript/323-countComponents.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function buildGraph(n, edges) {
2+
const graph = Array.from({ length: n }, () => []);
3+
4+
for (let edge of edges) {
5+
let [a, b] = edge;
6+
7+
if (!(a in graph)) graph[a] = [];
8+
if (!(b in graph)) graph[b] = [];
9+
10+
graph[a].push(b);
11+
graph[b].push(a);
12+
}
13+
return graph;
14+
}
15+
16+
var countComponents = function (n, edges) {
17+
const graph = buildGraph(n, edges);
18+
let count = 0;
19+
let visited = new Set();
20+
21+
function explore(graph, current, visited) {
22+
if (visited.has(current.toString())) return;
23+
24+
visited.add(current.toString());
25+
26+
for (let neighbor of graph[current]) {
27+
explore(graph, neighbor, visited);
28+
}
29+
return true;
30+
}
31+
32+
for (let node in graph) {
33+
if (explore(graph, node, visited)) {
34+
count += 1;
35+
}
36+
}
37+
return count;
38+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy