图的最短路径问题

  1. 无权图的单源最短路径算法(邻接表存储)

(相似于图的遍历的广度优先算法)

 1 typedef int Vertex;
 2 void UnWeighted(LGraph Graph,Vertex S){
 3     int i;
 4     ListNode W;
 5     int Dist[MaxVertexNumber],Path[MaxVertexNumber];//Dist存储到源点S的最短距离,Path存储到源点S路径
 6     Queue Q;
 7     Q=CreatQueue(Graph->Nn);
 8     for(i=0;iNn;i++){
 9         Dist[i]=Path[i]=-1;   //将Dist和Path初始化为-1
10     }
11     Dist[S]=0;
12     AddQ(Q,S);
13     while(!IsEmpty(Q)){
14         V=DeleteQ(Q);
15         for(W=Graph->G[V].FirstEdge;W;W=W.next){
16             if(Dist[W->AdjV]==-1){
17                 Dist[W->AdjV]=Dist[V]+1;
18                 Path[W->AdjV]=V;
19                 AddQ(Q,W->AdjV);
20             } 
21         }
22     }
23 }

 

 2.有权图的单源最短路径算法(邻接矩阵存储)

 

 1 typedef int Vertex;
 2 #define Infinity 10000;
 3 int Dist[VertexMaxNum],Path[VertexMaxNum];
 4 Vertex FindMinDist(MGraph Graph,int Dist[],int Collected[]){
 5     MinDist=Infinity;
 6     Vertex V,MinV;
 7     for(V=0;VNv;V++){
 8         if(Collected[V]==false && Dist[V]<MinDist){
 9             MinV=V;
10             MinDist=Dist[V];
11         }
12     }
13     if(MinDist<Infinity){
14         return MinV;
15     }
16     else{
17         return ERRORS;
18     }
19 }
20 bool Dijkstra(MGraph Graph,int Dist[],int Path[],Vertex S){
21     bool Collected[VertexMaxNum];
22     Vertex V,W;
23     for(V=0;VNv;V++){
24         Dist[V]=Graph->G[S][V];//默认邻接矩阵中不存在的边用INFINITY表示
25         Path[V]=-1;
26         if(G[S][V]<Infinity){
27             Path[V]=S;
28         }
29         Collected[V]=false;
30     }
31     Dist[S]=0;
32     Collected[S]=true;
33     Collected[V]=true;
34     while(1){
35         V=FindMinDist(Graph,Dist,Collected);
36         Collected[V]=true;
37         if(V==ERRORS){
38             break;
39         }
40         for(W=0;WNv;W++){
41             if(G[V][M]<0) return false;
42             if(Graph->G[V][M]false){
43                 if(Dist[V]+Graph[V][W]<Dist[W]){
44                    Dist[W]=Dist[V]+Graph[V][W];
45                    Path[W]=V;
46                 }   
47             }
48         }
49     }
50     return true;
51 }

 3.有权图多源最短路径算法

1,若有Nv个顶点,将Dijkstra算法调用N遍

2,folyd算法(不能有负值圈)

 1 bool Floyd(MGraph Graph,int Dist[][],Vertex Path[][] ){
 2     Vertex i,j,k;
 3     for(i=0;iNv;i++){
 4         for(j=0;jNv;j++){
 5             Dist[i][j]=Graph->G[i][j];
 6             Path[i][j]=-1;
 7         }
 8     }
 9     for(k=0;kNv;k++){
10         for(i=0;iNv;i++){
11             for(j=0;jNv;j++){
12                 if(Dist[i][k]+Dist[k][j]<Dist[i][j]){
13                     Dist[i][j]=Dist[i][k]+Dist[k][j];
14                     if(i==j && Dist[i][j]<0) return false; //有负值,返回错误
15                     Path[i][j]=k;
16                 }
17             }
18         }
19     }
20     return true;
21 }

 

你可能感兴趣的:(图的最短路径问题)