Min Spanning Tree-Prim‘s Algorithm-解法

这是一个关于求解最小生成树的问题,可以使用Prim或Kruskal算法。以下是Prim算法的实现,详细介绍了算法的时间复杂度和如何将二维平面上的点通过曼哈顿距离进行连接。给定一组坐标点,返回使所有点相连的最小总距离。问题转化为寻找最小联通路径,采用局部最优思想,逐步将距离当前集合最近的点加入,以构建全局最优解。此过程将图转换为树形结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:

"""
This is a typical minimum spanning tree question, it can be solved using either Kruskal or Prim's algorithm
Below is a Prim's algorithm implementation
Here is a wiki for Pirm's algorithm https://en.wikipedia.org/wiki/Prim's_algorithm
Time Complexity: Prim's Algorithm takes O(NlgN) but the whole solution is dominated by O(N*N) due to graph creation (nested loop)

You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.

Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
"""
 

from typing import List
import collections
import heapq


class Solution:

    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        res = 0
        n = len(points)
        q = [(0, 0)]
        dist = [float('inf')] * n
        mst = set()  #已纳入路径点
        while q:
            # 1. pop min node which is not in mst
            w, min_idx = heapq.heappop(q)
            if min_idx in mst:
                continue  # node was already added to the mst set

            # 2 add min node to mst
            res += w
            mst.add(min_idx)

            # 3. update min distance for neighbors in graph if not in mst and add to heap
            for v in range(n):
                if v not in mst:
                    d = abs(points[v][0] - points[min_idx][0]) + abs(points[v][1] - points[min_idx][1])
                    if d < dist[v]:
                        dist[v] = d
                        heapq.heappush(q, (d, v))
        return res

    def prim_distance(self,points):

        res=0
        n=len(points)
        dist=[float('inf')]*n
        mst=set()
        q=[(0,0)]
        while q:
            w,min_idx=heapq.heappop(q)
            if min_idx in mst:
                continue
            res+=w
            mst.add(min_idx)

            for v in range(n):
                if v in mst:
                    continue
                d=abs(points[v][0]-points[min_idx][0])+abs(points[v][1]-points[min_idx][1])
                if d<dist[v]:
                    dist[v]=d
                    heapq.heappush(q,(d,v))
        return res

题意:计算给定集合坐标的最小距离的连接路径, 点的距离即为权重

本质:求最小联通路径,利用prim算法,局部最优思想,往集合中一个个的加点,加的点要是全局点中,到已入集合点的距离最小的。这样串起来,就将局部最优与全局最优保持了一致.

         由于最优距离,随着目标集合的变化而变化,所以通过 下标-最短距离的方式,作为动态数组,不断更新.

应用: 图通过最短距离形式,转为树形结构

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值