![](/img/trans.png)
[英]Can i use the bfs technique for finding the shortest path in an undirected weighted graph? Instead of dijkstra's algo?
[英]I modified BFS to find shortest path in weighted undirected graph instead using Dijkstra's algo and it worked
為了在無向加權圖中找到最短路徑,我比較了 BFS 和 dijkstra 的算法,以了解為什么我們需要優先級隊列。
我寫了一些修改 BFS 的代碼來找到給定圖中所有節點的最短路徑。
問題鏈接:- https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1#
以下代碼在我編寫的 GeeksForGeeks 上被接受,而不是 dijkstra 算法:-
vector <int> dijkstra(int vertices, vector<vector<int>> graph[], int src)
{
// modified bfs
vector<int> dist(vertices + 1,INT_MAX);
queue<int> nodes;
nodes.push(src);
dist[src] = 0;
while(!nodes.empty()){
int curNode = nodes.front();
nodes.pop();
for(auto adjNode : graph[curNode]){
if(dist[adjNode[0]] > dist[curNode] + adjNode[1] ){
dist[adjNode[0]] = dist[curNode] + adjNode[1];
nodes.push(adjNode[0]);
}
}
}
return dist;
}
問題:- 雖然它在 GeeksForGeeks 上被接受了,但我想知道這可能是錯誤的,因為 GeeksForGeeks 可能只有有限數量的測試用例?
問題:- 或者,如果它是一種正確的方法,那么時間復雜度是多少? (想知道可能是因為時間復雜度比 dijkstra algo 上面的方法沒有使用)
您編寫的算法是Bellman-Ford Algorithm的變體。
Shortest_Path_Faster_Algorithm是 Bellman–Ford 算法(以及您的算法)的改進。 SPFA 和您的算法之間的唯一區別是 SPFA 在推送頂點之前檢查頂點是否已經在隊列中。 但它的最壞情況時間復雜度仍然是 O(V^2)。
考慮這個簡單的情況,每次訪問一個新頂點時,您都會更新從該頂點到頂點#2 的長鏈。
30
┌───────2
│ │ 1
│ 20 │
├───────3
│ │ 1
│ 15 │
1───┼───────4
│ │ 1
│ 12 │
├───────5
│ │ 1
│ 10 │
└───────6
SPFA 有許多其他優化變體,但其中大多數的最壞情況時間復雜度比 Dijkstra 算法更差。 一個簡單的隨機加權網格形狀圖可以使它們中的大多數運行得比 Dijkstra 算法慢得多。
更新:
SPFA 和 Dijkstra 算法在 grid-shap graph 上的簡單比較(現場演示):
dijkstra 27ms spfa 216ms (V=300*300 E~=3V on https://godbolt.org/z/b8qbWdbEP)
dijkstra 12ms spfa 87ms (V=300*300 E~=3V on my computer)
dijkstra 152ms spfa 4819ms (V=1000*1000 E~=3V on my computer)
更新 2 :
修改了生成器(現場演示)以對垂直邊緣使用固定的小權重。 SPFA 變得慢得多,這可以更直觀地估計其時間復雜度。
dijkstra 12ms spfa 393ms (V=200*200 on https://godbolt.org/z/hKnMqPvMM)
dijkstra 7ms spfa 192ms (V=200*200 on my computer)
dijkstra 15ms spfa 653ms (V=300*300 on my computer)
dijkstra 187ms spfa 40351ms (V=1000*1000 on my computer)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.