#include
#include
#include
#include
using
namespace std;
const
int inf = int_max;
void
dijkstra
(int n,
int s, vectorint>> graph, vector<
bool
>
&visited,
vector<
int>
&dist, vector<
int>
&path)
dist[s]=0
;for
(int i =
0; i < n; i++)}
// 找不到小於inf的dist[u],說明剩下的頂點與起點s不連通
if(u ==-1
)// 找到了u,則加入集合
visited[u]
=true
;// 遍歷所有頂點,如果v未在集合中 && 可以通過u訪問v && 通過u訪問v使得dist[v]更小
for(
int v =
0; v < n; v++)}
}}// printpath輔助函式
void
printpath_t
(int s,
int v, vector<
int> path)
printpath_t
(s, path[v]
, path)
; cout << v <<
" ";
}// 輸出從起點s到頂點v的最短路徑
void
printpath
(int s,
int v, vector<
int> path, vector<
int> dist)
cout <<
"the shortest path between "
<< s <<
" and "
<< v <<
" is: "
;printpath_t
(s, v, path)
; cout << endl;
}int
main()
,,,,
,}; vector<
int>
dist
(n);
vector<
int>
path
(n);
vector<
bool
>
visited
(n);
dijkstra
(n, s, graph, visited, dist, path)
;for
(int i =
0; i < n; i++)}
return0;
}
執行結果:
the shortest distance between 0 and 1 is: 4
the shortest path between 0 and 1 is: 0 1
the shortest distance between 0 and 2 is: 7
the shortest path between 0 and 2 is: 0 5 2
the shortest distance between 0 and 3 is: 5
the shortest path between 0 and 3 is: 0 4 3
the shortest distance between 0 and 4 is: 1
the shortest path between 0 and 4 is: 0 4
the shortest distance between 0 and 5 is: 2
the shortest path between 0 and 5 is: 0 5
參考鏈結
dijkstra演算法的實際應用
Dijkstra求單源最短路徑
思路 dijkstra求解帶權有向圖的單源最短路徑問題。與bellman ford演算法的區別是要求圖中沒有負的權值邊。在這種情況下dijkstra演算法通常有比較好的複雜度。特別是使用堆以後。演算法維護乙個點集s,該集合中的結點的最短路徑已經求出,演算法重複從結點集v s中選擇最短路徑估計最小的結...
Dijkstra求單源最短路徑
leetcode743 預定義 define mvnum 100 define imax 88888 無窮大 鄰接矩陣 typedef structmgraph 構造鄰接矩陣 int locatevex amgraph g,vertextype v return 1 int creategraph ...
Dijkstra演算法求單源最短路徑
與prim演算法樸素版實現起來差不多。樸素版dijkstra演算法 輸入乙個圖的矩陣,假定兩點不相鄰則權值為0 輸出每個頂點的最短路徑長度,可以列印指定頂點的路徑 dijkstra演算法跟prim演算法很像 相同的地方是 兩者都有乙個已經求得 mst 和已經求得 最短路 的集合 每納入乙個結點x到集...