Leetcode 1584. Min Cost to Connect All Points [Python]

并查集,也考察最小生成树科鲁斯卡算法。把每两个点的距离算出,以三元组形式储存,以距离大小做排序。然后以edge的数量为指标做while循环,弹出三元组,做Union操作,可以Union的,距离加入最后res,增加一条边。

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        p = [i for i in range(len(points))]
        
        def find(a):
            if a != p[a]:
                p[a] = find(p[a])
            return p[a]
        
        def union(a, b):
            pa = find(a)
            pb = find(b)
            p[pb] = pa
            return
        
        if len(points) == 1: return 0
        dic = collections.defaultdict(list)
        heap = []
        for i in range(len(points)):
            for j in range(i+1, len(points)):
                dis = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
                heap.append((dis, i, j))
                
        heap.sort(key = lambda x:x[0])
        count = 0
        res = 0
        while count < len(points)-1:
            dis, x, y = heap.pop(0)
            if find(x) != find(y):
                union(x, y)
                res += dis
                count += 1
        return res
        

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值