哪个python包实现了BellmanFord最短路径算法?

2024-10-05 22:45:13 发布

您现在位置:Python中文网/ 问答频道 /正文

哪个python包实现了Bellman-Ford最短路径算法?在

给定一个起始节点i和一个具有负权重的邻接矩阵G,我想找到从i到另一个节点j的最短路径。例如,我的图如下所示:

import numpy
G = numpy.array([[ 0.  ,  0.55,  1.22],
                 [-0.54,  0.  ,  0.63],
                 [-1.3 , -0.63,  0.  ]])

我只能找到一个all-pairs shortest path实现,它对于我的需求来说太浪费了,因为我的图很大,而且我只需要一对节点的最短路径。性能对我来说是很重要的,因为我会把它用于成千上万的图形。在

因此,我四处寻找贝尔曼福特的实现-有人见过吗?在


Tags: pathimport路径numpy算法节点浪费all
1条回答
网友
1楼 · 发布于 2024-10-05 22:45:13

滚我自己的

def bellmanFord(source, weights):
    '''
    This implementation takes in a graph and fills two arrays
    (distance and predecessor) with shortest-path (less cost/distance/metric) information

    https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
    '''
    n = weights.shape[0]

    # Step 1: initialize graph
    distance = np.empty(n)
    distance.fill(float('Inf'))      # At the beginning, all vertices have a weight of infinity
    predecessor = np.empty(n)
    predecessor.fill(float('NaN'))   # And a null predecessor

    distance[source] = 0             # Except for the Source, where the Weight is zero

    # Step 2: relax edges repeatedly
    for _ in xrange(1, n):
        for (u, v), w in np.ndenumerate(weights):
        if distance[u] + w < distance[v]:
        distance[v] = distance[u] + w
    predecessor[v] = u

    # Step 3: check
    for negative - weight cycles
    for (u, v), w in np.ndenumerate(weights):
        if distance[u] + w < distance[v]:
        raise ValueError("Graph contains a negative-weight cycle")

    return distance, predecessor

相关问题 更多 >