1319. 连通网络的操作次数(傻瓜教程)(python)(LC)

1319. 连通网络的操作次数

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

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

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


示例 1:

输入:n = 4, connections = [[0,1],[0,2],[1,2]]
输出:1
解释:拔下计算机 12 之间的线缆,并将它插到计算机 13 上。

示例 2:

输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
输出:2

示例 3:

输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
输出:-1
解释:线缆数量不足。

示例 4:

输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
输出:0

思路:并查集

一、因为涉及到0-(n-1)中每一个元素,所以我们无需添加add()方法,且可以采用并查集模版暴力构图

二、对“拔线”的理解体现为对是否构成“环”对判断,为了方便,我们取消isconnected()方法,并把它插入union()方法中

三、添加“more”元素作为结果的衡量,本质上,“more”是对union()方法中isconnected()元素的计数

四、根据题意输出结果

完整代码

class UF:
    def __init__(self, n):
        self.parent = {i: i for i in range(n)}
        self.cnt = n
        self.more = 0

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while x != root:
            original_parent = self.parent[x]
            self.parent[x] = root
            x = original_parent
        return root

    def union(self, x, y):
        leader_x = self.find(x)
        leader_y = self.find(y)
        if leader_x != leader_y:
            self.parent[leader_x] = leader_y
            self.cnt -= 1
        else:
            self.more += 1

class Solution:
    def makeConnected(self, n: int, connections) -> int:
        uf = UF(n)
        for x, y in connections:
            uf.union(x, y)
        if uf.more >= uf.cnt - 1:
            return uf.cnt -1
        elif uf.more < uf.cnt - 1:
            return -1
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grayson Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值