如何在此关键路径算法中记录路径(Python Floyd Warshall)

2024-09-27 19:30:36 发布

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

我正在写一个代码来寻找“nxn”矩阵中所有对之间的最短路径。因此,我的代码似乎正在运行并返回最短路径。但是现在我想记录顶点之间的路径,而不仅仅是最短距离。示例-城市1和44之间的最短路径耗时5天。现在我想知道它所采用的路径,在本例中为1-->;5-->;12-->;44.

# The number of vertices
nV = len(G)-1
print(range(nV))
INF = 999

# Algorithm implementation
def floyd_warshall(G):
    distance = list(map(lambda i: list(map(lambda j: j, i)), G))

    # Adding vertices individually
    for k in range(nV):
        for i in range(nV):
            for j in range(nV):
                distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
    print_solution(distance)


cobalt = list(map(lambda i: list(map(lambda j: j, i)), G))

# Printing the solution
def print_solution(distance):
    for i in range(nV):
        for j in range(nV):
            if(distance[i][j] == INF):
                print("INF", end=" ")
            else:
                print(distance[i][j], end="  ")
            cobalt[i][j] = distance[i][j]            
        print(" ")


abcd = np.asarray(cobalt)
np.savetxt("foo.csv", abcd, delimiter=",")

floyd_warshall(G)

Tags: lambda代码ingt路径mapforrange
1条回答
网友
1楼 · 发布于 2024-09-27 19:30:36

对Floyd Warshall算法进行修改:
保留一对(distance, k),其中k是更新距离值的中间顶点,而不仅仅是距离。k的默认值为-1

if distance[i][j][0] > distance[i][k][0] + distance[k][j][0]:
    distance[i][j] = (distance[i][k][0] + distance[k][j][0], k)

可以通过递归重构任何最短路径

def get_path(i, j):
    if distance[i][j] == +oo: # oo stand for infinite
        return []             # None is also an option
    k = distance[i][j][1]
    if k == -1:
        return [i, j]
    else:
        path = get_path(i, k)
        path.pop()            # remove k to avoid duplicates
        path.extend(get_path(k, j))
        return path

运行时:O(length of path)

注意:从xy的最小成本路径的要求是,从xy的任何路径之间都不存在负成本周期

相关问题 更多 >

    热门问题