Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf9cb77c

Browse files
authored
Merge pull requestneetcode-gh#377 from anthonysim/asim/connectedComponents
323 js countComponents
2 parents708ba00 +e91f8a8 commitf9cb77c

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+
functionbuildGraph(n,edges){
2+
constgraph=Array.from({length:n},()=>[]);
3+
4+
for(letedgeofedges){
5+
let[a,b]=edge;
6+
7+
if(!(aingraph))graph[a]=[];
8+
if(!(bingraph))graph[b]=[];
9+
10+
graph[a].push(b);
11+
graph[b].push(a);
12+
}
13+
returngraph;
14+
}
15+
16+
varcountComponents=function(n,edges){
17+
constgraph=buildGraph(n,edges);
18+
letcount=0;
19+
letvisited=newSet();
20+
21+
functionexplore(graph,current,visited){
22+
if(visited.has(current.toString()))return;
23+
24+
visited.add(current.toString());
25+
26+
for(letneighborofgraph[current]){
27+
explore(graph,neighbor,visited);
28+
}
29+
returntrue;
30+
}
31+
32+
for(letnodeingraph){
33+
if(explore(graph,node,visited)){
34+
count+=1;
35+
}
36+
}
37+
returncount;
38+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp