首页 > 代码库 > dijkstra求最短路

dijkstra求最短路

dijkstra和Prim很像,区别在于Prim在找到离MST最近的结点后把它加入MST并更新与此结点相邻的结点离MST的最短距离;而dijsktra中,找到当前离起点最近的结点后,更新与它相邻的结点距离起点的最短距离和最短路径。

代码如下:

 1 //dijkstra
 2 #include <iostream>
 3 #include <cstring>
 4 #include <vector>
 5 using namespace std;
 6 
 7 const int INF=0x3f3f3f3f;
 8 
 9 struct Edge{
10     int vertex, weight;
11 };
12 
13 class Graph{
14 private:
15     int n;
16     vector<Edge> *edges;
17     bool *visited;
18 public:
19     int *prev;     //stores index of previous node
20     int *dist;     //stores min dist of a node to the starting node
21     Graph(int input_n){
22         n=input_n;
23         edges=new vector<Edge>[n];
24         prev=new int[n];
25         dist=new int[n];
26         visited=new bool[n];
27         memset(prev,-1,n*sizeof(int));
28         memset(visited,0,n);
29         memset(dist,0x3f,n*sizeof(int));
30     }
31     ~Graph(){
32         delete[] edges;
33         delete[] visited;
34         delete[] prev;
35         delete[] dist;
36     }
37     void insert(int x, int y, int weight){
38         edges[x].push_back(Edge{y,weight});
39         edges[y].push_back(Edge{x,weight});
40     }
41     void dijkstra(int start_v){
42         dist[start_v]=0;
43         //every time settle one vertex
44         for(int i=0;i<n;i++){
45             int min_dist=INF, min_vertex = 0;
46             //find the current nearest vertex
47             for(int j=0;j<n;j++){
48                 if(!visited[j]&&dist[j]<min_dist){
49                     min_dist=dist[j];
50                     min_vertex=j;
51                 }
52             }
53             visited[min_vertex]=1;
54             //update shortest dist of adjcent vertices
55             //and update previous node, which is min_vertex
56             for(Edge &j: edges[min_vertex]){
57                 if(min_dist+j.weight<dist[j.vertex]){
58                     dist[j.vertex]=min_dist+j.weight;
59                     prev[j.vertex]=min_vertex;
60                 }
61             }
62         }
63     }
64     void printPath(int cur_v){
65         if(prev[cur_v]!=-1){
66             printPath(prev[cur_v]);
67         }
68         cout<<cur_v<<"  ";
69     }
70 };
71 
72 int main() {
73     int n, m;
74     cin >> n >> m;
75     Graph g(n);
76     for (int i = 0; i < m; i++) {
77         int a, b, c;
78         cin >> a >> b >> c;
79         g.insert(a, b, c);
80     }
81     g.dijkstra(0);
82     for (int i = 0; i < n; i++) {
83         cout << i << ": " << g.dist[i] << endl;
84     }
85     for(int i=0;i<n;i++){
86         g.printPath(i);
87         cout<<endl;
88     }
89     return 0;
90 }

 

dijkstra求最短路