Kruskal算法适合于稀疏图(贪心)
Prim算法适合于稠密图或者完全图
连接所有点的最小费用def root(x):
if p[x]!=x:
p[x]=root(p[x])
return p[x]
def union(x,y):
if root(x)==root(y):
return False
if root(x)!=root(y):
p[root(x)]=root(y)
return True
points = [[3,12],[-2,5],[-4,1]]
dist = lambda x, y: abs(points[x][0] - points[y][0]) + abs(points[x][1] - points[y][1])
n = len(points)
p=[int(i) for i in range(n+1)]
edges =[]
for i in range(n):
for j in range(i + 1, n):
edges.append((dist(i, j), i, j))
edges.sort()
ans, num = 0, 1
for length, x, y in edges:
if union(x, y):
ans += length
num += 1
if num == n:
break
print(ans)
最低成本联通所有城市
到达目的地的方案数
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)