Skip to content

Commit aae3ae1

Browse files
Solve : Number of Connected Components in an Undirected Graph
1 parent 44381e9 commit aae3ae1

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import (
2+
List,
3+
)
4+
5+
class Solution:
6+
def count_components(self, n: int, edges: List[List[int]]) -> int:
7+
parent = [i for i in range(n)]
8+
def find(x):
9+
if parent[x] != x:
10+
parent[x] = find(parent[x])
11+
return parent[x]
12+
for a, b in edges:
13+
root_a = find(a)
14+
root_b = find(b)
15+
if root_a != root_b:
16+
parent[root_a] = root_b
17+
n -= 1
18+
return n

0 commit comments

Comments
 (0)