# Bellman_Ford最短路径算法

``````import numpy as np
dist=np.array([[0,1,1,0.5,0,0],[1,0,0,1,1,0],[1,0,0,1,1,1],[0.5,1,1,0,1,0],[0,1,1,1,0,1],[0,0,1,0,1,0]])
def bf(adjacent_array,source):
weight = adjacent_array
node_num = len(adjacent_array[0])
path = list(range(node_num))
distance = [float("inf") for i in range(node_num)]
distance[source-1] = 0

i = 0
while i < node_num:
j = i
while j < node_num:
if weight[i][j]:
if distance[i]+weight[i][j]<distance[j]:
distance[j] = distance[i]+weight[i][j]
path[j] = i
j += 1
i += 1
i = 0
while i < node_num:
path_to = [i+1]
j = i
while j != source-1:
path_to.insert(0,path[j]+1)
j = path[j]
print("the path to %d is:"%(i+1))
print(path_to)
i += 1
print(distance)
bf(dist,1)
``````
``````<< 运行结果如下
the path to 1 is:
[1]
the path to 2 is:
[1, 2]
the path to 3 is:
[1, 3]
the path to 4 is:
[1, 4]
the path to 5 is:
[1, 4, 5]
the path to 6 is:
[1, 3, 6]
[0, 1.0, 1.0, 0.5, 1.5, 2.0]``````
原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/Muyan_Donny/article/details/80987319
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。