Created
May 31, 2023 14:10
-
-
Save Desolve/40a58853d50c6c18acded10bee487bac to your computer and use it in GitHub Desktop.
0547 Number of Provinces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def findCircleNum(self, edges: List[List[int]]) -> int: | |
n = len(edges) | |
root = [i for i in range(n)] | |
rank = [1] * n | |
def find(i): | |
r = root[i] | |
while r != root[r]: | |
root[r] = root[root[r]] | |
r = root[r] | |
root[i] = r | |
return r | |
def union(x, y): | |
rx, ry = find(x), find(y) | |
if rx == ry: | |
return False | |
if rank[rx] >= rank[ry]: | |
rank[rx] += rank[ry] | |
root[ry] = rx | |
else: | |
rank[ry] += rank[rx] | |
root[rx] = ry | |
return True | |
for i in range(n): | |
for j in range(i + 1, n): | |
if edges[i][j] == 1: | |
union(i, j) | |
res = set() | |
for i in root: | |
res.add(find(i)) | |
return len(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment