在做leetcode399题除法求值时用到了并查集,在这里把模版贴出来记录一下。
class UnionFind:
def __init__(self):
self.father = {} ##记录每个节点的父节点
def find(self, x):
root = x
while self.father[root] != root: #寻找根节点
root = self.father[root]
while root != x: #路径压缩
preFather = self.father[x]
self.father[x] = root
x = preFather
return root
def merge(self, x, y): #合并节点
root_x, root_y = self.find(x), self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
def is_connected(self, x, y): #判断联通性
return self.find(x) == self.find(y)
def add(self, x): #增加节点
if x not in self.father:
self.father[x] = x