繁体   English   中英

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

[英]How to record the path in this critical path algo (Python - Floyd Warshall)

我正在编写代码来查找“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)

对 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM