https://www.bilibili.com/video/BV1Eb41177d1?spm_id_from=333.337.search-card.all.click
强推,一下看懂了
_ = float('inf') # 正无穷
def prim(graph,n):
dist=[_]*n # 记录最短权值
visit=[False]*n # 记录是否连通(去过)
preIndex=[0]*n # 记录每次寻找的起点
# # 第一个顶点
# visit[0] = True
# for i in range(n): # 相邻的边权值
# dist[i] = graph[0][i]
# 找到当前无向图的最小生成树
for i in range(n):
mindist=_+1
nextIndex = 0
# 扫描Scan:找到基于当前i,i行中哪一列距离最小作为下一个节点,前提是那个节点没有去过
for j in range(n):
if dist[j]< mindist and not visit[j]: # visit[j] == False
mindist = dist[j]
nextIndex =j
visit[nextIndex]= True # 添加Add
# 更新Update:由于前面找到下一个节点了,下面构建下一个节点的dist矩阵,要看nextIndex这一行
for j in range(n):
if dist[j]>graph[nextIndex][j] and not visit[j]: # visit[j] == False
dist[j]=graph[nextIndex][j]
preIndex[j]=nextIndex
return dist,preIndex
if __name__=='__main__':
n=6
# A到B的权重是6
graph=[[0,6,3,_,_,_],
[6,0,2,5,_,_],
[3,2,0,3,4,_],
[_,5,3,0,2,3],
[_,_,4,2,0,5],
[_,_,_,3,5,0]]
dist,preIndex=prim(graph,n)
print(dist)
print(preIndex)
[inf, 2, 3, 3, 2, 3]
[0, 2, 0, 2, 3, 3]
给定带权无向图,求出一颗最小的生成树。
输入格式:
输入多组测试数据。第一行为N,M,依次是点数和边数。接下来M行,每行三个整数U,V,W,代表连接U,V的边,和权值W。保证图连通。n=m=0标志着测试文件的结束。
输出格式:
对于每组数据,输出方差,四舍五入到0.01。输出格式按照样例。
# 图初始化
N,M = map(int,input().split())
_ = float('inf')
graph =[[_ for i in range(N)]for i in range(N)]
# 读图
for i in range(M):
U,V,W = map(int,input().split())
graph[U-1][V-1] = W
for i in range(N):
graph[i][i] = 0
print(graph)
4 5
1 2 1
2 3 2
3 4 2
4 1 1
2 4 3
[[0, 1, inf, inf], [inf, 0, 2, 3], [inf, inf, 0, 2], [1, inf, inf, 0]]
# 读图
_ = float('inf')
def Prim(graph,n):
dist=[_]*n #记录最短权值
preIndex=[0]*n #记录出发点
visit=[False]*n #记录是否访问过
for i in range(n):
# 扫描Scan
mindist = _
nextIndex = -1
for j in range(n):
if dist[j] < mindist and not visit[j]:
mindist = dist[j]
nextIndex = j
# 添加Add
# preIndex[i] = nextIndex
visit[nextIndex] = True
# 更新Update
for j in range(n):
if dist[j] > graph[nextIndex][j] and not visit[j]:
dist[j] = graph[nextIndex][j]
preIndex[i] = nextIndex
return dist,preIndex
if __name__=='__main__':
n=6
# A到B的权重是6
graph=[[0,6,3,_,_,_],
[6,0,2,5,_,_],
[3,2,0,3,4,_],
[_,5,3,0,2,3],
[_,_,4,2,0,5],
[_,_,_,3,5,0]]
dist,preIndex=prim(graph,n)
print(dist)
print(preIndex)
[inf, 2, 3, 3, 2, 3]
[0, 2, 0, 2, 3, 3]
① 二维数组初始化 graph =[[_ for i in range(N)]for i in range(N)]
② 初始化。一个访问与否bool visit,一个起始节点,一个最短路径。
③ 扫描Scan,添加Add,更新Update