def floyd_warshall(G):
nodes=len(G)
dis=[row[:] for row in G]
#一共需要进行nodes次数跟新
for k in range(nodes):
for i in range(nodes):
for j in range(nodes):
"""
如果D[v][k] + D[k][w] 为更小值,
则把D[v][k] + D[k][w] 覆盖保存在D[v][w]中
"""
"""
if C->B->A->G
dis(C,G)=dis(C,B)+dis(B,G)
dis(B,G)=dis(B,A)+dis(A,G)
每个循环内只保留单步更新
"""
if dis[i][k]+dis[k][j]<dis[i][j]:
dis[i][j]=dis[i][k]+dis[k][j]
return dis
if __name__=="__main__":
inf=float('inf')
G= [
[0, 3, inf, inf, inf],
[2, 0, inf, inf, inf],
[inf, 7, 0, 1, inf],
[6, inf, inf, 0, 2],
[inf, inf, inf, inf, 0]]
shortest_paths = floyd_warshall(G)
source = 2#以c作为圆点
nodes = ['A', 'B', 'C', 'D', 'E'] # 节点名称
print(f"选择{nodes[source]}作为源点:")
for i in range(len(shortest_paths)):
if i != source: # 只打印到其他节点的距离
destination = nodes[i]
distance = shortest_paths[source][i]
if distance == inf:
print(f"{nodes[source]}到{destination}的距离为: No path")
else:
print(f"{nodes[source]}到{destination}的距离为: {distance}")
单源最短路径Floyd算法实现
最新推荐文章于 2025-04-12 16:30:03 发布