单源最短路径Dijkstra算法

1.单源最短路径

函数:返回还未被收录顶点中dist最小者

 1 Vertex FindMinDist(MGraph Graph, int dist[], int collected[])
 2 {
 3     /*返回未被收录顶点中dist最小者*/
 4     Vertex MinV, V;
 5     int MinDist = INFINITY;
 6 
 7 
 8     for (V = 0; V < Graph->Nv; ++V)
 9     {
10         if (collected[V] == false && dist[V] < MinDist)
11         {
12             MinDist = dist[V];
13             MinV = V;                //更新对应顶点
14         }
15     }
16     if (MinDist < INFINITY)            //若找到最小值
17         return MinV;
18     else
19         return -1;
20 }
单源最短路径Dijkstra算法
 1 /*单源最短路径Dijkstra算法*/
 2 /*dist数组存储起点到这个顶点的最小路径长度*/
 3 bool Dijkstra(MGraph Graph, int dist[], int path[], Vertex S)
 4 {
 5     int collected[MaxVertexNum];
 6     Vertex V, W;
 7 
 8     /*初始化,此处默认邻接矩阵中不存在的边用INFINITY表示*/
 9     for (V = 0; V < Graph->Nv; V++)
10     {
11         dist[V] = Graph->G[S][V];            //用S顶点对应的行向量分别初始化dist数组
12         if (dist[V] < INFINITY)                //如果(S, V)这条边存在
13             path[V] = S;                //将V顶点的父节点初始化为S
14         else
15             path[V] = -1;                //否则初始化为-1
16         collected[V] = false;            //false表示这个顶点还未被收入集合
17     }
18 
19 
20     /*现将起点S收录集合*/
21     dist[S] = 0;                //S到S的路径长度为0
22     collected[S] = true;
23 
24     while (1)
25     {
26         V = FindMinDist(Graph, dist, collected);    //V=未被收录顶点中dist最小者
27         if (V == -1)        //如果这样的V不存在
28             break;
29         collected[V] = true;        //将V收录进集合
30         for (W = 0; W < Graph->Nv; W++)        //对V的每个邻接点
31         {
32             /*如果W是V的邻接点且未被收录*/
33             if (collected[W] == false && Graph->G[V][W] < INFINITY)
34             {
35                 if (Graph->G[V][W] < 0)        //若有负边,不能正常解决,返回错误标记
36                     return false ;
37                 if (dist[W] > dist[V] + Graph->G[V][W])
38                 {
39                     dist[W] = dist[V] + Graph->G[V][W];        //更新dist[W]
40                     path[W] = V;            //更新S到W的路径
41                 }
42             }
43         }
44     }
45     return true;
46 }

猜你喜欢

转载自www.cnblogs.com/hi3254014978/p/10078111.html