[英]Weighted Directed Graph best method for shortest path
對於我正在做的一個問題,我很困惑為什么答案是 BFS 而不是 Dijkstra 的算法。
問題是:有一個加權有向圖 G=(V,E),具有 n 個節點和 m 個邊。 每個節點的權重為 1 或 2。問題是要找出使用哪種算法在 G 中找到從給定頂點 u 到給定頂點 v 的最短路徑。選項有:
a) O(n+m) time using a modified BFS
b) O(n+m) time using a modified DFS
c) O(mlogn) time using Dijkstra's Algorithm
d) O(n^3) time using modified Floyd-Warshall algorithm
答案是 a) O(n+m) 時間使用修改后的 BFS,
我知道在將 BFS 與 DFS 進行比較時,BFS 更適合較短的路徑。 我也知道 Dijkstra 的算法類似於 BFS,如果我沒記錯的話,Dijkstra 的算法更適合這種情況下的加權圖。 我假設 BFS 更好,因為它說修改后的 BFS,但修改的確切含義是什么,或者還有另一個原因 BFS 會更好。
Since all paths are limited to either a distance of 1 or 2, for every edge of length 2 from nodes a
to b
you can just create a new node c
with an edge from a
to c
of length 1 and an edge from c
to b
長度為 1,然后這變成一個只有權重為 1 的邊的圖,通常可以BFS
找到從u
到v
的最短路徑。 由於您只添加了O(m)
個新節點和O(m)
個新邊,因此 BFS 的時間復雜度為O(n+m)
。
另一種可能性是,在 BFS 的每一層,存儲另一個節點列表,這些節點由當前層的權重為 2 的邊獲得,並與稍后獲得兩層的節點同時考慮它們。 這種方法雖然有點挑剔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.