Leetcode:547. 省份数量(python3)

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



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值