2020-12-0611:43:13
问题描述:
编写一个程序,采用迪杰斯特拉算法,输出下图所示的有向带权图G中顶点0到达其他各个顶点的最短路径长度和最短路径。
1
#include 2 #define MAXV 100 //最大顶点个数
3 #define INF 32767 //用32767表示无穷大
4 //typedef int InfoType
5 typedef struct
6 {
7 int no; //顶点编号
8 int info; //顶点其他信息,这里用于存放边的权值
9 }VertexType; //顶点类型
10 typedef struct
11 {
12 int edges[MAXV][MAXV]; //邻接矩阵
13 int vexnum, arcnum; //顶点数,弧数
14 VertexType vexs[MAXV]; //存放顶点信息
15 }MGragh; //图的邻接矩阵类型
16 void DispMat(MGragh g) //输出邻接矩阵g
17 {
18 int i, j;
19 for (i = 0; i )
20 {
21 for (j = 0; j )
22 if (g.edges[i][j] == INF)
23 printf("%3s", "∞");
24 else
25 printf("%3d", g.edges[i][j]);
26 printf("\n");
27 }
28 }
29 void ppath(int path[], int i, int v0) // 输出各条最短路径
30 {
31 int k;
32 k = path[i];
33 if (k == v0)
34 return;
35 ppath(path, k, v0);
36 printf("%d,", k);
37 }
38 void DisPath(int dist[], int path[], int s[], int n, int v0)
39 // 由path计算最短路径
40 {
41 int i;
42 printf("path:"); //输出path值
43 for (i = 0; i )
44 printf("%3d", path[i]);
45 printf("\n");
46 for (i = 0; i )
47 if (s[i] != 0 && i != v0)
48 {
49 printf("从%d到%d的最短路径长度为:%d\t路径为:", v0, i, dist[i]);
50 printf("%d,", v0);
51 ppath(path, i, v0);
52 printf("%d\n", i);
53 }
54 else
55 printf("从%d到%d不存在路径\n", v0, i);
56 }
57 void Dijkstra(MGragh g, int v0)
58 //狄克斯特拉算法求得从顶点v0到其余各顶点的最短路径
59 {
60 int dist[MAXV], path[MAXV];
61 int s[MAXV];
62 int mindis, i, j, u, n = g.vexnum;
63 for (i = 0; i )
64 {
65 dist[i] = g.edges[v0][i]; //距离初始化
66 s[i] = 0; //s[]置空
67 if (g.edges[v0][i] //路径初始化
68 path[i] = v0;
69 else
70 path[i] = -1;
71 }
72 s[v0] = 1; path[v0] = 0; //源点编号v0放入s中
73 for (i = 0; i //循环直到所有顶点的最短路径都求出
74 {
75 mindis = INF;
76 u = -1;
77 for (j = 0; j //选取不在s中且具有最小距离的顶点
78 if (s[j] == 0 && dist[j] mindis)
79 {
80 u = j;
81 mindis = dist[j];
82 }
83 s[u] = i; //顶点u加入s中
84 for (j = 0; j //修改不在s中的顶点的距离
85 if (s[j] == 0)
86 if (g.edges[u][j] dist[j])
87 {
88 dist[j] = dist[u] + g.edges[u][j];
89 path[j] = u;
90 }
91 }
92 printf("输出最短路径:\n");
93 DisPath(dist, path, s, n, v0); //输出最短路径
94 }
95 void main()
96 {
97 int i, j, u = 0;
98 MGragh g;
99 int A[MAXV][6] = {
100 {INF,5,INF,7,INF,INF},
101 {INF,INF,4,INF,INF,INF},
102 {8,INF,INF,INF,INF,9},
103 {INF,INF,5,INF,INF,INF},
104 {INF,INF,INF,5,INF,INF},
105 {3,INF,INF,INF,1,INF} };
106 g.vexnum = 6;
107 g.arcnum = 9;
108 for (i = 0; i //建立如图所示的邻接矩阵
109 for (j = 0; j )
110 g.edges[i][j] = A[i][j];
111 printf("\n");
112 printf("有向图G的邻接矩阵:\n");
113 DispMat(g);
114 Dijkstra(g, u);
115 printf("\n");
116 }