Skip to content

Commit

Permalink
Merge pull request neetcode-gh#374 from ironnicko/main
Browse files Browse the repository at this point in the history
Added Python Code for Number of Connected Components In An Undirected…
  • Loading branch information
neetcode-gh authored Jul 6, 2022
2 parents aa43937 + 4a8cade commit f72c149
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 43-Number_of_Connected_Components_in_an_Undirected_Graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

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 f72c149

Please sign in to comment.