栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python并查集模板

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python并查集模板

模板
class UnionFind():
    def __init__(self,n):
        self.parent=list(range(n))
        self.count=n   #记录组数
    def find(self,node):  #查找node的父节点
        while node!=self.parent[node]:
            self.parent[node]=self.parent[self.parent[node]] #路径压缩
            node=self.parent[node]
        return node
    def union(self,node1,node2):  #将两个node合并为一组
        node1father=self.find(node1)
        node2father=self.find(node2)
        if node1father!=node2father:
            self.parent[node1father]=node2father
            self.count-=1
        return
例题

力扣547 省份数量

class UnionFind():
    def __init__(self,n):
        self.parent=list(range(n))
        self.count=n
    def find(self,node):
        while node!=self.parent[node]:
            self.parent[node]=self.parent[self.parent[node]]
            node=self.parent[node]
        return node
    def union(self,node1,node2):
        node1father=self.find(node1)
        node2father=self.find(node2)
        if node1father!=node2father:
            self.parent[node1father]=node2father
            self.count-=1
        return

class Solution:
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        n=len(isConnected)
        uf=UnionFind(n)
        for i in range(n):
            for j in range(n):
                if isConnected[i][j]==1:
                    uf.union(i,j)
        return uf.count


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/302608.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号