Skip to content

Added Python Code for Number of Connected Components In An Undirected… #374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 6, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy