class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
if isConnected is None:
return 0
uf = UnionFind(isConnected)
row,col = len(isConnected), len(isConnected[-1])
for i in range(row):
for j in range(col):
if j == i:
continue
if isConnected[i][j]== 1:
uf.union(i,j)
return uf.get_count()
class UnionFind:
def __init__(self, grid) -> None:
city_count = len(grid)
self.root = [-1]*city_count
self.count = city_count
for i in range(city_count):
self.root[i] = i
def find(self,x):
if x == self.root[x]:
return self.root[x]
else:
# quick find
self.root[x] = self.find(self.root[x])
return self.root[x]
def union(self, x, y):
rootx = self.find(x)
rooty = self.find(y)
if rootx != rooty:
self.root[rootx] = rooty
self.count -=1
def get_count(self):
return self.count