首页 > 编程语言 > 详细

并查集的Python 实现

时间:2021-09-06 05:04:18      阅读:11      评论:0      收藏:0      [点我收藏+]
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 实现

原文:https://www.cnblogs.com/11aaa/p/15228030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!