并查集python版本模版

这篇博客介绍了如何运用并查集数据结构来解决LeetCode上的399题。文中提供了详细的并查集模版代码,包括初始化、查找、合并、联通性判断和添加节点等操作,对于理解和应用并查集解决实际问题有很好的参考价值。

在做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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值