这是一种简单的动态规划算法。
让我们假设我们想要从顶点开始x
到顶点y
.
做一个表D[.,.]
, where D[v,k]
是长度最短路径的成本k
从起始顶点x
到顶点v
.
Initially D[x,1] = 0. Set D[v,1] = infinity for all v != x.
For k=2 to n:
D[v,k] = min_u D[u,k-1] + wt(u,v), where we assume that wt(u,v) is infinite for missing edges.
P[v,k] = the u that gave us the above minimum.
最短路径的长度将存储在 D[y,n] 中。
如果我们有一个边较少的图(稀疏图),我们可以通过仅搜索来有效地做到这一点u
that v
连接到。这可以通过邻接列表数组来最佳地完成。
恢复最短路径:
Path = empty list
v = y
For k= n downto 1:
Path.append(v)
v = P[v,k]
Path.append(x)
Path.reverse()
最后一个节点是y
。之前的节点是P[y,n]
。我们可以一直向后追踪,最终会到达P[v,2] = x
对于一些v
.