def bellman_ford( graph, source ):
distance = {}
parent = {}
for node in graph:
distance[node] = float( 'Inf' )
parent[node] = None
distance[source] = 0
for i in range( len( graph ) - 1 ):
for from_node in graph:
for to_node in graph[from_node]:
if distance[to_node] > graph[from_node][to_node] + distance[from_node]:
distance[to_node] = graph[from_node][to_node] + distance[from_node]
parent[to_node] = from_node
for from_node in graph:
for to_node in graph[from_node]:
if distance[to_node] > distance[from_node] + graph[from_node][to_node]:
return None, None
return distance, parent
def test():
graph = {
'a': {'b': -1, 'c': 4},
'b': {'c': 3, 'd': 2, 'e': 2},
'c': {},
'd': {'b': 1, 'c': 5},
'e': {'d': -3}
}
distance, parent = bellman_ford( graph, 'a' )
print distance
print parent
if __name__ == '__main__':
test()
bellman_ford算法 python实现
原文作者:Bellman - ford算法
原文地址: https://blog.csdn.net/pandora_madara/article/details/22752333
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/pandora_madara/article/details/22752333
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。