具体原理可以参考链接1 视频讲解
python实现如下
# dist是任意两点之间的最短路径,path是这两点之间的最短路径,所需途径的点
def floyd_warshall(graph):
n = len(graph)
dist = [[float('inf')] * n for _ in range(n)]
path = [[-1] * n for _ in range(n)]
# 初始化距离矩阵和路径矩阵
for i in range(n):
for j in range(n):
if i == j:
dist[i][j] = 0
elif graph[i][j] != 0:
dist[i][j] = graph[i][j]
elif graph[i][j] == 0 and i!=j:
dist[i][j] = float('inf')
# Floyd-Warshall 算法
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] != float('inf') and dist[k][j] != float('inf'):
new_dist = dist[i][k] + dist[k][j]
if new_dist < dist[i][j]:
dist[i][j] = new_dist
path[i][j] = k
return dist, path
# 示例图
graph = [[0, 5, 10, 0, 0],
[0, 0, 1, 2, 0],
[0, 0, 0, 0, 4],
[0, 0, 3, 0, 0],
[0, 0, 0, 6, 0]]
dist, path = floyd_warshall(graph)
print(f"dist={dist},\npath = {path},\ngraph={graph}\n")
# 打印距离矩阵
print("Distances:")
for row in dist:
print(row)
# 打印路径矩阵
print("\nPaths:")
for row in path:
print(row)
# 打印顶点对之间的最短路径
def print_shortest_path(src, dest, path):
if path[src][dest] == -1:
if dist[src][dest] != float('inf'):
print(src, end=" -> ")
print(dest)
else:
print(f"src不可达dest!!!")
else:
mid = path[src][dest]
print_shortest_path(src,mid,path)
print_shortest_path(mid,dest,path)
# # 示例:打印顶点 0 到顶点 4 的最短路径
print("\npath:")
print_shortest_path(1, 4, path)
graph如下图所示
运行结果
root@localhost:~/code/floyd# python3 floyd.py
dist=[[0, 5, 6, 7, 10], [inf, 0, 1, 2, 5], [inf, inf, 0, 10, 4], [inf, inf, 3, 0, 7], [inf, inf, 9, 6, 0]],
path = [[-1, -1, 1, 1, 2], [-1, -1, -1, -1, 2], [-1, -1, -1, 4, -1], [-1, -1, -1, -1, 2], [-1, -1, 3, -1, -1]],
graph=[[0, 5, 10, 0, 0], [0, 0, 1, 2, 0], [0, 0, 0, 0, 4], [0, 0, 3, 0, 0], [0, 0, 0, 6, 0]]
Distances:
[0, 5, 6, 7, 10]
[inf, 0, 1, 2, 5]
[inf, inf, 0, 10, 4]
[inf, inf, 3, 0, 7]
[inf, inf, 9, 6, 0]
Paths:
[-1, -1, 1, 1, 2]
[-1, -1, -1, -1, 2]
[-1, -1, -1, 4, -1]
[-1, -1, -1, -1, 2]
[-1, -1, 3, -1, -1]
path:
1 -> 2
2 -> 4