我看过很多帖子(即。post1 https://stackoverflow.com/questions/30409493/using-bfs-for-weighted-graphs, post2 https://cs.stackexchange.com/questions/18138/dijkstra-algorithm-vs-breadth-first-search-for-shortest-path-in-graph, post3 https://stackoverflow.com/questions/3818079/why-use-dijkstras-algorithm-if-breadth-first-search-bfs-can-do-the-same-thing)关于这个主题,但没有一篇文章提供了备份各自查询的算法。因此,我不确定是否接受这些帖子的答案。
在这里,我提出了一种基于 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
Runtime:据我所知,它是 O(|V| + |E|) ,包括初始化成本
如果该算法与现有算法类似,请告诉我