原题:
"""
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算法,局部最优思想,往集合中一个个的加点,加的点要是全局点中,到已入集合点的距离最小的。这样串起来,就将局部最优与全局最优保持了一致.
由于最优距离,随着目标集合的变化而变化,所以通过 下标-最短距离的方式,作为动态数组,不断更新.
应用: 图通过最短距离形式,转为树形结构