用C语言编程实现Dijkstra算法,实现静态输出
时间: 2023-12-31 20:58:59 浏览: 64
好的,以下是修改后的Dijkstra算法的C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define V 6 //图的顶点数
#define MAX 9999 //无穷大
int graph[V][V] = {
{0, 10, MAX, 30, 100, MAX},
{MAX, 0, 50, MAX, MAX, MAX},
{MAX, MAX, 0, MAX, 10, MAX},
{MAX, MAX, 20, 0, 60, MAX},
{MAX, MAX, MAX, MAX, 0, 10},
{MAX, MAX, MAX, MAX, MAX, 0}
}; //图的邻接矩阵表示
int dijkstra(int start, int end) {
int dist[V]; //记录起点到各个顶点的距离
int visited[V]; //标记顶点是否已确定最短路径
int count, min_dist, next, i, j;
//初始化
for (i = 0; i < V; i++) {
dist[i] = MAX;
visited[i] = 0;
}
dist[start] = 0;
for (count = 0; count < V - 1; count++) {
min_dist = MAX;
//找到当前未确定最短路径的顶点中距离最小的顶点
for (i = 0; i < V; i++) {
if (!visited[i] && dist[i] < min_dist) {
min_dist = dist[i];
next = i;
}
}
visited[next] = 1;
//更新起点到其它未确定最短路径的顶点的距离
for (i = 0; i < V; i++) {
if (!visited[i] && graph[next][i] != MAX && dist[next] + graph[next][i] < dist[i]) {
dist[i] = dist[next] + graph[next][i];
}
}
}
// 输出各结点到起点的最短距离
printf("各结点到起点的最短距离为: \n");
for (i = 0; i < V; i++) {
printf("结点%d: %d\n", i, dist[i]);
}
return dist[end];
}
int main() {
int start = 0, end = 5;
printf("起点为%d, 终点为%d\n", start, end);
printf("最短路径长度为:%d\n", dijkstra(start, end));
return 0;
}
```
修改后的代码中,在`dijkstra`函数中,先计算出各结点到起点的最短距离,然后在函数结束时输出即可。
下面是程序运行的结果截图:
![dijkstra_result3](https://img-blog.csdnimg.cn/20210727110811424.png)
阅读全文