This algorithm is very similar to the idea root algorithm Primm (Prim) algorithm of minimum spanning tree. The Didgers algorithm is the shortest path algorithm for finding vertices to other vertices.
The following code: (using the adjacency matrix notation)
Dijkstra Shortest path. Shortest path from vex vertex to other vertex void Shortestpath_dij (mgraph g,char vex) {int loc = graphlocation (g,vex); int Minarray[max_vertex_num ]={0};//Minimum Path value bool Final[max_vertex_num] = {false};//has completed minimum path//initialization vex to vex data minarray[loc] = 0;final[loc] = True;int p ath[max_vertex_num][max_vertex_num];//path array, each row holds the shortest path vex to this line int pathlenarray[max_vertex_num] = {0};// Stores the number of path arrays per row. for (int i = 0; i < G.vexnum; i++) {Minarray[i] = g.arcs[loc][i].adj;if (Minarray[i] < INFINITY) {//vex points to Ipath[i][0] = i;pathlenarray[i] = 1;}} for (int i = 1; i < g.vexnum; i++)//g.vernum-1 path {int min = infinity;//minimum path value int minindex = -1;//Current minimum path index int notfind = -1;for (int i = 0; i < G.vexnum; i++) {//in Minarray search for the lowest value (excluding completed) if (final[i] = False) {if (Minarray[i] < min) { Min = Minarray[i];minindex = i;} Else{notfind = i;}} else if (final[i] = = False) {//not found. Notfind = i;}} if (Minindex = =-1) {//no path special handling Minindex = Notfind;} Final[minindex] = true;//setting has found the minimum path//print minimum path, and the minimum path value if (minindex! = notfind) {printf ("%c To%c, the minimum Path value is:%d, the path is:%c ", Vex,g.vexs[minindex],min,vex);} else{printf ("%c to%c unreachable", Vex,g.vexs[minindex],min,vex);} int minlen = pathlenarray[minindex];for (int i = 0; i < Minlen; i++) {printf ("→%c", G.vexs[path[minindex][i]]);} printf ("\ n"); for (int i = 0; i < G.vexnum; i++) {//Recalculate minimum path array if (final[i] = false) {int newmin = min + G.arcs[mininde X][i].adj;if (Newmin < minarray[i]) {Minarray[i] = newmin;//re-set path int j;for (j = 0; J < Pathlenarray[minindex]; J + +) { PATH[I][J] = path[minindex][j];} PATH[I][J] = I;pathlenarray[i] = j+1;//Sets the array length.}}}}
Two questions were encountered while writing this code:
1. Numerical overflow, the Int_max used in the book, to indicate an unreachable relationship between vertices.
When recalculating the minimum path array, int newmin = min + G.arcs[minindex][i].adj; If Int_max is encountered, then the code is logically chaotic.
So I turned the int_max into a short-integer.
#define INFINITY Shrt_max
2. Code in the book when the minimum value is not found, then accessing the final array will overflow the stack. Added a special treatment.
if (Minindex = =-1) {//no path special handling Minindex = Notfind;}
Full source code Web address: Click to open the link
Run:
See Data structure Write code (47) Dijkstra Shortest Path algorithm