File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 311
311
320|[ Generalized Abbreviation] ( ./solutions/0320-generalized-abbreviation.js ) |Medium|
312
312
321|[ Create Maximum Number] ( ./solutions/0321-create-maximum-number.js ) |Hard|
313
313
322|[ Coin Change] ( ./solutions/0322-coin-change.js ) |Medium|
314
+ 323|[ Number of Connected Components in an Undirected Graph] ( ./solutions/0323-number-of-connected-components-in-an-undirected-graph.js ) |Medium|
314
315
324|[ Wiggle Sort II] ( ./solutions/0324-wiggle-sort-ii.js ) |Medium|
315
316
326|[ Power of Three] ( ./solutions/0326-power-of-three.js ) |Easy|
316
317
327|[ Count of Range Sum] ( ./solutions/0327-count-of-range-sum.js ) |Hard|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 323. Number of Connected Components in an Undirected Graph
3
+ * https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
4
+ * Difficulty: Medium
5
+ *
6
+ * You have a graph of n nodes. You are given an integer n and an array edges where
7
+ * edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.
8
+ *
9
+ * Return the number of connected components in the graph.
10
+ */
11
+
12
+ /**
13
+ * @param {number } n
14
+ * @param {number[][] } edges
15
+ * @return {number }
16
+ */
17
+ var countComponents = function ( n , edges ) {
18
+ const parent = new Array ( n ) . fill ( ) . map ( ( _ , i ) => i ) ;
19
+ let components = n ;
20
+
21
+ for ( const [ node1 , node2 ] of edges ) {
22
+ union ( node1 , node2 ) ;
23
+ }
24
+
25
+ return components ;
26
+
27
+ function find ( node ) {
28
+ if ( parent [ node ] !== node ) {
29
+ parent [ node ] = find ( parent [ node ] ) ;
30
+ }
31
+ return parent [ node ] ;
32
+ }
33
+
34
+ function union ( node1 , node2 ) {
35
+ const root1 = find ( node1 ) ;
36
+ const root2 = find ( node2 ) ;
37
+ if ( root1 !== root2 ) {
38
+ parent [ root1 ] = root2 ;
39
+ components -- ;
40
+ }
41
+ }
42
+ } ;
You can’t perform that action at this time.
0 commit comments