Skip to content

Commit

Permalink
Added Python Code for Number of Connected Components In An Undirected…
Browse files Browse the repository at this point in the history
… Graph
  • Loading branch information
ironnicko authored Jul 6, 2022
1 parent 19c46e4 commit 393b654
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions number_of_connected_components_in_an_undirected_graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import List


class Solution:
def count_components(self, n: int, edges: List[List[int]]) -> int:
parent = [i for i in range(n)]
rank = [1] * n

def find_union(node: int) -> None:
result = node
while result != parent[result]:
parent[result] = parent[parent[result]] # path compression
result = parent[result]
return result

def union(node_1: int, node_2: int):
parent_1 = find_union(node_1)
parent_2 = find_union(node_2)
if parent_1 == parent_2:
return 0
if rank[parent_2] < rank[parent_1]:
parent[parent_1] = parent_2
rank[parent_2] += rank[parent_1]
else:
parent[parent_2] = parent_1
rank[parent_1] += rank[parent_2]
return 1

result = n
for node_1, node_2 in edges:
result -= union(node_1, node_2)
return result

0 comments on commit 393b654

Please sign in to comment.