我对 Bellman-Ford 算法正确性的实现是错误的吗?

问题描述

我正在学习本教程:Bellman-Ford Algorithm by Jessica Su 并实现了算法 2

enter image description here

如下:

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

该片段在最后一个测试用例中失败了,图形如下所示:

enter image description here

在这种情况下,更新机制不能保证 memorization_table[i] 保存了最小值,因为有两条路径并且它们没有被比较。

所以不知道是伪代码不对还是我的实现不对?

解决方法

讲义中算法的伪代码在这一行有一个错误:

?? ← min{??−1[?],??−1[?] + ?(?,?) )} // 更新 v 的估计

这将使?? 的值仅依赖于最后访问的边(?,?)。 ?? 对 ? 的任何先前访问过的边的影响将被覆盖。

相反,这一行应该是:

?? ← min{??[?],?)} // 更新 v 的估计

这样??的值就变成了所有??−1[?] + ?(?,?)