floyd算法解析+python实现

本文详细介绍了Floyd-Warshall算法在Python中的实现,包括算法原理、距离矩阵和路径矩阵的初始化,以及如何使用该算法找到任意两点之间的最短路径。通过示例展示了算法在给定图上的运行结果。
摘要由CSDN通过智能技术生成

具体原理可以参考链接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
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值