如何解决我对 Bellman-Ford 算法正确性的实现是错误的吗?
我正在学习本教程:Bellman-Ford Algorithm by Jessica Su 并实现了算法 2
如下:
def negative_cycle(adj,cost):
"""
detect negative cycle in a graph
reference: https://web.stanford.edu/class/archive/cs/cs161/cs161.1168/lecture14.pdf
param adj: list of list,index represent nodes,and values the edges starting from them
param cost: list of list,and values the corresponding weights of edges
return 0 or 1: 1 represents that there is at least 1 negative cycle in the graph
>>> negative_cycle([[1],[2],[0],[0]],[[-5],[1],[2]])
1
>>> negative_cycle([[1],[3],[[2],[2]])
0
>>> negative_cycle([[1,3],[],[2]],[[3,7],[4],[5]])
0
"""
vertex_num = len(adj)
memorization_table = np.matrix(np.ones((vertex_num,vertex_num)) * np.inf)
memorization_table[:,0] = 0.0
for i in range(1,vertex_num):
for u in range(0,vertex_num):
for j,v in enumerate(adj[u]):
memorization_table[i,v] = min(memorization_table[i-1,v],memorization_table[i-1,u]+cost[u][j])
for u in range(0,vertex_num):
for j,v in enumerate(adj[u]):
if memorization_table[i,v] > memorization_table[i-1,u]+cost[u][j]:
return 1
return 0
完整代码为here。
该片段在最后一个测试用例中失败了,图形如下所示:
在这种情况下,更新机制不能保证 memorization_table[i]
保存了最小值,因为有两条路径并且它们没有被比较。
所以不知道是伪代码不对还是我的实现不对?
解决方法
讲义中算法的伪代码在这一行有一个错误:
?? ← min{??−1[?],??−1[?] + ?(?,?) )} // 更新 v 的估计
这将使?? 的值仅依赖于最后访问的边(?,?)。 ?? 对 ? 的任何先前访问过的边的影响将被覆盖。
相反,这一行应该是:
?? ← min{??[?],?)} // 更新 v 的估计
这样??的值就变成了所有??−1[?] + ?(?,?)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。