File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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)
You can’t perform that action at this time.
0 commit comments