-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy path547-number-of-provinces.py
42 lines (37 loc) · 1.21 KB
/
547-number-of-provinces.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class UnionFind:
def __init__(self, n):
self.parent = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
self.count = n
def find(self, p):
while p != self.parent[p]:
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
def union(self, p, q):
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q:
return
if self.rank[root_p] > self.rank[root_q]:
self.parent[root_q] = root_p
elif self.rank[root_p] < self.rank[root_q]:
self.parent[root_p] = root_q
else:
self.parent[root_p] = root_q
self.rank[root_q] += 1
self.count -= 1
def get_count(self):
return self.count
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
uf = UnionFind(n)
for p in range(n):
for q in range(n):
if isConnected[p][q]:
uf.union(p, q)
return uf.get_count()
# time O(n**2), using path compression and union by rank can reduce cost to near O(1)
# space O(n)
# using graph and union find