File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
graphs/union-find/number-of-connected-components Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+ def find_parent (i : int , components : List [int ]) -> int :
4+
5+ while i != components [i ]:
6+ i = components [i ]
7+ return i
8+
9+
10+ class Graph :
11+ def number_of_connected_components (self , edges_matrix : List [List [int ]]) -> int :
12+
13+ n : int = len (edges_matrix )
14+
15+ number_of_components : int = n
16+
17+ components : List [int ] = [None ] * n
18+
19+ for i in range (n ):
20+ components [i ] = i
21+
22+ for i in range (n ):
23+
24+ for j in range (n ):
25+
26+ if edges_matrix [i ][j ] == 1 :
27+
28+ parent_one : int = find_parent (i , components )
29+ parent_two : int = find_parent (j , components )
30+
31+ if parent_one != parent_two :
32+ components [parent_one ] = parent_two
33+ number_of_components -= 1
34+
35+ return number_of_components
You can’t perform that action at this time.
0 commit comments