Floyd-Warshall 算法:获取最短路径

2024-05-09

假设一个图由一个表示n x n维数邻接矩阵。我知道如何获得所有对的最短路径矩阵。但我想知道有没有办法追踪所有最短路径? Blow是python代码实现。

v = len(graph)
for k in range(0,v):
    for i in range(0,v):
        for j in range(0,v):
            if graph[i,j] > graph[i,k] + graph[k,j]:
                graph[i,j] = graph[i,k] + graph[k,j]

您必须在 if 语句中添加一个新矩阵来存储路径重建数据(数组p这是前驱矩阵):

    if graph[i,j] > graph[i,k] + graph[k,j]:
        graph[i,j] = graph[i,k] + graph[k,j]
        p[i,j] = p[k,j]

一开始的矩阵p必须填写为:

for i in range(0,v):
    for j in range(0,v):
        p[i,j] = i
        if (i != j and graph[i,j] == 0):
             p[i,j] = -30000  # any big negative number to show no arc (F-W does not work with negative weights)

重建之间的路径i and j您必须调用的节点:

def ConstructPath(p, i, j):
    i,j = int(i), int(j)
    if(i==j):
      print (i,)
    elif(p[i,j] == -30000):
      print (i,'-',j)
    else:
      ConstructPath(p, i, p[i,j]);
      print(j,)

并用上述函数进行测试:

import numpy as np

graph = np.array([[0,10,20,30,0,0],[0,0,0,0,0,7],[0,0,0,0,0,5],[0,0,0,0,10,0],[2,0,0,0,0,4],[0,5,7,0,6,0]])

v = len(graph)

# path reconstruction matrix
p = np.zeros(graph.shape)
for i in range(0,v):
    for j in range(0,v):
        p[i,j] = i
        if (i != j and graph[i,j] == 0): 
            p[i,j] = -30000 
            graph[i,j] = 30000 # set zeros to any large number which is bigger then the longest way

for k in range(0,v):
    for i in range(0,v):
        for j in range(0,v):
            if graph[i,j] > graph[i,k] + graph[k,j]:
                graph[i,j] = graph[i,k] + graph[k,j]
                p[i,j] = p[k,j]

# show p matrix
print(p)

# reconstruct the path from 0 to 4
ConstructPath(p,0,4)

Output:

p:

[[ 0.  0.  0.  0.  5.  1.]
 [ 4.  1.  5.  0.  5.  1.]
 [ 4.  5.  2.  0.  5.  2.]
 [ 4.  5.  5.  3.  3.  4.]
 [ 4.  5.  5.  0.  4.  4.]
 [ 4.  5.  5.  0.  5.  5.]]

路径0-4:

0
1
5
4
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Floyd-Warshall 算法:获取最短路径 的相关文章

随机推荐