File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +36
-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 : number , edges : number [ ] [ ] ) : number {
8+ const parent = Array . from ( { length : n } , ( _ , i ) => i ) ;
9+ let components = n ;
10+
11+ const find = ( i : number ) : number => {
12+ if ( parent [ i ] === i ) {
13+ return i ;
14+ }
15+
16+ parent [ i ] = find ( parent [ i ] ) ;
17+ return parent [ i ] ;
18+ } ;
19+
20+ const union = ( a : number , b : number ) : void => {
21+ const rootA = find ( a ) ;
22+ const rootB = find ( b ) ;
23+
24+ if ( rootA !== rootB ) {
25+ parent [ rootA ] = rootB ;
26+ components -- ;
27+ }
28+ } ;
29+
30+ for ( const [ a , b ] of edges ) {
31+ union ( a , b ) ;
32+ }
33+
34+ return components ;
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments