Figure-Shortest path (data structure)

The shortest path algorithm of the graph 

// Dijkstra's algorithm: find the shortest path from one vertex to the other
// Freud algorithm: path between any pair of vertices
1 #include <iostream>
 2  using  namespace std;
 3  // The shortest path
 4  
5  // Dijstra ’s algorithm: find the shortest path from a vertex to the remaining vertices 
6  void printfPath ( int path [], int a) { // Output path algorithm 
7      int stack [maxsize], top = -1 ;
 8      while (path [a]! = -1 ) {
 9          stack [++ top] = path [a];
 10          a = path [a ];
 11      }
 12      while (top! = -1 ) {
13         cout<<stack[top--]<<" ";
14     }
15     cout<endl;
16 } 
17 void Dijkstra(MGraph g,int v,int dist[],int path[]){
18     int set[maxsize];
19     int k,min;
20     for(int i=0;i<g.n;i++){//初始化 
21         dist[i]=g.edges[v][i];
22         set[i]=0;
23         if(g.edges[v][i]<INF){
24             path[i]=v;
25         }else{
26             path[i]=-1;
27         }
28     }
29     set[v]=1;
30     path[v]=-1;
31     for(int i=0;i<g.n-1;i++){//两层循环 
32         min=INF;
33         for(int j=0;j<g.n;j++){//Find the next vertex and put it into the set 
34              if ( set [j] == 0 && dist [j] < min) {
 35                  k = j;
 36                  min = dist [j];
 37              }
 38          }
 39          set [k] = 1 ;
 40          for ( int j = 0 ; j <gn; j ++) { // Update the shortest path 
41              if ( set [j] == 0 && dist [j]> dist [k] + edges [k] [j]) {
 42                  dist [j] = dist [k] + edges [k] [j];
 43                 path [j] = k;
 44              }
 45          }
 46      }
 47  } 
 48  
49  // Freud algorithm: path between any pair of vertices 
50  void printPath ( int u, int v, int path [] [maxsize]) { // Output path 
51      if (path [u] [v] ==- 1 ) {
 52          cout << u << " -> " << v << endl;
 53          return ;
 54      }
 55      else {
 56          int mid=path[u][v];
57         printPath(u,mid,path);
58         printPath(mid,v,path);
59     }
60 } 
61 void Floyd(MGraph g,int path[][maxsize]){//复杂度为N^3; 
62     int A[maxsize][naxsize];
63     for(int i=i;i<g.n;i++){//对A[][]和path[][]初始化 
64         for(int j=0;j<g.n;j++){
65             A[i][j]=g.edges[i][j];
66             path[i][j]=-1;
 67          }
 68      }
 69      for ( int k = 0 ; k <gn; k ++) { // The three-layer loop completes the detection and modification of all i, j with K as the intermediate point. 
70          for ( int i = 0 ; i <gn; i ++ ) {
 71              for ( int j = 0 ; j <gn; j ++ ) {
 72                  if (A [i] [j]> A [i] [k] + A [k] [j]) {
 73                      A [i] [j] = A [i] [K] + A [k] [j];
 74                      path [i] [j] = k;
 75                  }
 76              }
77         }
78     }
79 }

 

Guess you like

Origin www.cnblogs.com/aiqinger/p/12707249.html