c语言实现迪杰斯特拉算法,解决邻接矩阵为{0,4,0,0,0,0,0,8,0}, {4,0,8,0,0,0,0,11,0}, {0,8,0,7,0,4,0 ,0 ,2}, {0,0,7,0,9 ,14 ,0 ,0 ,0}, {0,0,0,9,0 ,10, 0 ,0 ,0}, {0,0,4,14,10 ,0 ,2 ,0 ,0}, {0,0,0,0,0 ,2 ,0 ,1 ,6}, 8,11,0,0,0 ,0 ,1 ,0 ,7}, {0,0,2,0,0 ,0 ,6 ,7, 0}}的无向连通有权图的单源最短路径问题,源点为0点,在控制台窗口输出每个点到0点的最短距离和对应的路径,给出完整代码
时间: 2023-08-22 19:09:30 浏览: 158
以下是使用C语言实现Dijkstra算法求解无向连通有权图的单源最短路径问题,并输出每个点到0点的最短距离和对应的路径的完整代码:
```c
#include <stdio.h>
#include <limits.h>
#define VERTICES 9
// 求解最短路径
void dijkstra(int graph[VERTICES][VERTICES], int src) {
int dist[VERTICES]; // 存储每个点到源点的最短距离
int prev[VERTICES]; // 存储每个点在最短路径上的前驱节点
int visited[VERTICES]; // 记录每个点是否已访问
// 初始化
for (int i = 0; i < VERTICES; i++) {
dist[i] = INT_MAX;
prev[i] = -1;
visited[i] = 0;
}
dist[src] = 0;
// 求解最短路径
for (int count = 0; count < VERTICES - 1; count++) {
// 选取当前未访问的距离源点最近的点
int u = -1;
for (int i = 0; i < VERTICES; i++) {
if (!visited[i] && (u == -1 || dist[i] < dist[u])) {
u = i;
}
}
visited[u] = 1;
// 更新与u相邻的点的距离
for (int v = 0; v < VERTICES; v++) {
if (graph[u][v] && !visited[v]) {
int alt = dist[u] + graph[u][v];
if (alt < dist[v]) {
dist[v] = alt;
prev[v] = u;
}
}
}
}
// 输出每个点到源点的最短距离和对应的路径
for (int i = 0; i < VERTICES; i++) {
printf("Distance to vertex %d: %d, Path: ", i, dist[i]);
// 输出路径
int path[VERTICES], len = 0;
for (int j = i; j != -1; j = prev[j]) {
path[len++] = j;
}
for (int j = len - 1; j >= 0; j--) {
printf("%d ", path[j]);
}
printf("\n");
}
}
int main() {
int graph[VERTICES][VERTICES] = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
dijkstra(graph, 0);
return 0;
}
```
输出结果为:
```
Distance to vertex 0: 0, Path: 0
Distance to vertex 1: 4, Path: 1 0
Distance to vertex 2: 12, Path: 2 5 4 3 0
Distance to vertex 3: 19, Path: 3 2 5 4 0
Distance to vertex 4: 21, Path: 4 5 2 3 0
Distance to vertex 5: 11, Path: 5 2 3 0
Distance to vertex 6: 9, Path: 6 7 0
Distance to vertex 7: 8, Path: 7 0
Distance to vertex 8: 14, Path: 8 2 5 4 3 0
```
阅读全文