Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created May 31, 2023 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/40a58853d50c6c18acded10bee487bac to your computer and use it in GitHub Desktop.
Save Desolve/40a58853d50c6c18acded10bee487bac to your computer and use it in GitHub Desktop.
0547 Number of Provinces
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