leetcode 1319. 连通网络的操作次数 python 并查集

用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。

网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。

给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。

解法:使用并查集来统计计算机之间的连通情况,每合并一个不同根的就在独立的数里减1,同根的则在多余的线数里加1。最后如果线够了的画返回需要的线数即可。

class UnionFindSet():
    def __init__(self,n):
        self.setSize = n  #总节点数
        self.father = {}
        self.more = 0  #多余的线数

    def add(self,x):  #添加根节点
        if x not in self.father:
            self.father[x] = -1

    def find(self,x):
        root = x
        while self.father[root] != -1:  #找根节点
            root = self.father[root]

        while x != root: #路径压缩
            o = self.father[x]  #找x的父节点
            self.father[x] = root  #把x的父节点设置成刚才找到的根
            x = o  #往上一层

        return root

    def merge(self,x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x != root_y:
            self.father[root_x] = root_y  #合并
            self.setSize -= 1
        else:
            self.more += 1        
            
    def is_Union(self, x, y):
        return self.find(x) == self.find(y)



class Solution:
    def makeConnected(self, n: int, connections: List[List[int]]) -> int:
        uf = UnionFindSet(n)

        for x,y in connections:
            uf.add(x)
            uf.add(y)

            uf.merge(x, y)
        
        if uf.setSize - 1 <= uf.more:  #如果需要的线数比多的线数少或者一样多
            return uf.setSize - 1
        else:
            return -1
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值