我已经看过很多关于这个主题的帖子(即post1、post2、post3),但没有一个帖子提供了备份相应查询的算法。因此,我不确定接受这些帖子的答案。
在这里,我提出了一种基于 BFS 的最短路径(单源)算法,适用于非负加权图。谁能帮我理解为什么 BFS(根据以下基于 BFS 的算法)不用于此类问题(涉及加权图)!
算法:
SingleSourceShortestPath (G, w, s):
//G is graph, w is weight function, s is source vertex
//assume each vertex has 'col' (color), 'd' (distance), and 'p' (predecessor)
properties
Initialize all vertext's color to WHITE, distance to INFINITY (or a large number
larger than any edge's weight, and predecessor to NIL
Q:= initialize an empty queue
s.d=0
s.col=GREY //invariant, only GREY vertex goes inside the Q
Q.enqueue(s) //enqueue 's' to Q
while Q is not empty
u = Q.dequeue() //dequeue in FIFO manner
for each vertex v in adj[u] //adj[u] provides adjacency list of u
if v is WHITE or GREY //candidate for distance update
if u.d + w(u,v) < v.d //w(u,v) gives weight of the
//edge from u to v
v.d=u.d + w(u,v)
v.p=u
if v is WHITE
v.col=GREY //invariant, only GREY in Q
Q.enqueue(v)
end-if
end-if
end-if
end-for
u.col=BLACK //invariant, don't update any field of BLACK vertex.
// i.e. 'd' field is sealed
end-while
运行时:据我所知,它是 O(|V| + |E|) 包括初始化成本
如果此算法类似于任何现有算法,请告诉我