class UnionFind:
def __init__(self, n):
self.root = [i for i in range(n)]
self.rank = [1]*n
self.cnt = n # 用来统计孤岛个数
def find(self, x):
if x == self.root[x]:
return x
self.root[x] = self.find(self.root[x])
return self.root[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
if self.rank[root_x]>self.rank[root_y]:
self.root[root_y] = root_x
elif self.rank[root_x]<self.rank[root_y]:
self.root[root_x] = root_y
else:
self.root[root_y] = root_x
self.rank[root_x] +=1
self.cnt -=1 # 每次并集孤岛数量--1
def isConnected(self, x, y):
return self.find(x) == self.find(y)
并查集的Python 实现