Python图论算法(四)——bellman_ford

graph = [[0,1,3,6],
         [1,0,1,5],
         [3,1,0,2],
         [6,5,2,0]]

inf = 100000
n = 4
d = [0,inf,inf,inf]
p = [-1,-1,-1,-1]

def relax(a,b):
    if(d[b] > d[a] + graph[a][b]):
        d[b] = d[a] + graph[a][b]
        p[b] = a+1
for k in range(n-1):
    for i in range(n):
        for j in range(n):
            relax(i,j)
print d
print p
    

主要就是relax()的问题。多次循环,不停地relax()就好了。

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/u010352695/article/details/44679951
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞