The Dijksitra algorithm is only suitable for cases where there is no negative right (the Bellman-ford algorithm does not have this limitation). The main feature is to extend from the starting point to the outer layer until it expands to the end point.
Optimal substructure properties of shortest circuit
That is, all points passing through the shortest path are the shortest. (Contradiction easy license)
Dijkstra Basic Ideas:
① Find the shortest distance of the identified vertex, from which to update the shortest distance of adjacent vertices
② no longer need to care about the "apex of the shortest distance" in 1.
At the very beginning, only the shortest distance from the starting point is determined. In unused vertices, the smallest vertex of the distance d[i] is the vertex that has been determined for the shortest distance. because there is no negative edge , D[i] will not be smaller in subsequent updates. This is the Dijkstra algorithm.
Dijkstra algorithm code not optimized
intCOST[MAX_V][MAX_V];//Use adjacency matrix to store edges (no inf exists)intD[MAX_V];//Minimum distanceBOOLUSED[MAX_V];//has determined the shortest-circuit diagramintV//dijkstra AlgorithmvoidDijkstraints) {//InitializeFill (D,d+v,inf); Fill (Used,used+v,false); D[s] =0;//Shortest way while(true) {intv =-1; for(inti =0; i < V; i + +) {if(!used[i]) {if(v = =-1|| D[i] < d[v]) v = i; } }if(v = =-1) Break;//If you are sure, exitUSED[V] =true; for(inti =0; i < V; i + +) {D[i] =min(D[i],d[v]+cost[v][i]); } }}
Optimizing Code with Priority queues
#include <cstdio>#include <cstring>#include <algorithm>using namespace STD;structedge{intTo,cost;};typedefpair<int,int> P;//first is the shortest distance second is the vertex numberintV vector<edge>G[MAX_V];//adjacency tableintD[MAX_V];voidDijkstraints) {//By specifying the greater<p> parameter, the heap takes the value out of first order from small to largePriority_queue<p, vector<P>,greater<p>> que; Fill (D,d+v,inf); D[s] =0; Que.push (P (0, s)); while(!que.empty ()) {p p = que.top (); Que.pop ();intv = p.second;//Number if(D[v] < P.first)Continue; for(inti =0; I < g[v].size (); i + +) {Edge e = g[v][i];if(D[e.to] > D[v]+e.cost) {D[e.to] = D[v]+e.cost; Que.push (P (d[e.to],e.to)); } } }}
The complexity of the Dijkstra algorithm is O (| E|log| v|), the shortest path can be solved more efficiently. But if there is a negative edge or to use the Bellman-ford algorithm.
Shortest Path Dijkstra algorithm