The Dijstra algorithm is to find the shortest path from a vertex i to a large other vertex. The idea of the Distra algorithm is similar to the prim algorithm, and the rules that ingest vertices are collected in the order of the path length increment. Set V0 is the source vertex, we are looking for the shortest path from V0 to any other point. The set of vertices that have been solved (the vertices that have been found from v0 to the shortest path to the vertex) are s={v0,v1,... VK}; the next vertex v is either (v0,v) or (v0,vj,v), and if it is the latter, there must be vj∈s, This is easy to prove with the method of anyway. The time complexity of the Dijstra algorithm is O (v^2), if the sparse graph uses adjacency table storage instead, the minimum heap time complexity is O (ELOGV). The specific code is as follows (assuming the diagram is connected here) and has a corresponding explanation:
1#include <iostream>2 using namespacestd; 3 #defineMax_size 1004 #defineMax_number INT_MAX/25 structGraph {6 intV, E; 7 intW[max_size][max_size]; 8 }; 9 BOOLVisit[max_size]; Ten intDis[max_size]; One intParent[max_size]; A voidDijstra (Graph G,inti);//vertex i is the shortest distance from the starting point to other points - voidPrintpath (intj); - intMain () { the intI, j,w,k; - Graph G; - for(i =0; i < max_size; i++) - for(j =0; J < Max_size; J + +) +G.W[I][J] = (i = = j?)0: Max_number);//Diagonal Set to 0, other set to infinity -CIN >> G.V >>G.E; + for(k=0; k< G.E; k++) { ACin >> I >> J >>W; atG.W[I][J] = g.w[j][i]=W; - } -Dijstra (G,3); - for(i =0; i < G.V; i++) -printf"%d%d\n", I, dis[i]); -Printpath (6);//print the path to vertex 6 in return 0; - } to voidDijstra (Graph G,inti) { + intK, J,pos,min; -memset (Visit,0,sizeof(visit));//Initialize the for(j =0; J < G.V; J + +) *DIS[J] = Max_number;//first set the distance to infinity $j =i; Panax NotoginsengDIS[J] =0;//the distance to itself is 0 -PARENT[J] =-1;//I is the parent node theVISIT[J] =1;//First, the vertex I itself is included + for(i =1; i < G.V; i++) { A for(k =0; K < G.V; k++) {//update the effect of last included Vertex J on other vertices the if(!visit[k] && dis[k]>=dis[j] + g.w[j][k]) {//here G.w[j][k] before initializing do not set to Int_max, otherwise dis[j]+g.w[j][k] + //may exceed the range of int. -DIS[K] = Dis[j] +G.w[j][k]; $PARENT[K] =J; $ } - } -pos = j, min =Max_number; the for(k =0; K < G.V; k++) { - if(!visit[k] && min>Dis[k]) { Wuyipos =K; theMin =Dis[k]; - } Wu } -j =POS; AboutVISIT[J] =1;//the J included $ } - } - voidPrintpath (intj) { - if(j==-1) A return; + Printpath (Parent[j]); theprintf"%d", J); -}
Single source Shortest path Dijstra algorithm