File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments