实现Dijkstra算法,解决如下无向连通有权图的单源最短路径问题,源点为0点。int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 0, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 0, 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点的最短距离和对应的路径。 ,并用c语言实现
时间: 2023-09-29 19:08:09 浏览: 62
好的,这是一个经典的Dijkstra算法问题,可以用以下步骤来实现:
1. 创建一个大小为V的数组dist,用来存储每个点到0点的最短距离,初始值为无穷大,除了0点的距离为0。
2. 创建一个大小为V的数组visited,用来标记每个点是否被访问过,初始值为false。
3. 初始化dist[0]为0。
4. 对于每个点i(除了0点),找到距离0点最近的未访问过的点j,标记j为visited。
5. 对于每个与j相邻的未访问过的点k,如果通过j到达k比直接到k距离更短,则更新dist[k]为dist[j]+graph[j][k]。
6. 重复步骤4和5,直到所有点都被访问过。
以下是C语言实现的代码:
```c
#include <stdio.h>
#include <stdbool.h>
#define V 9
#define INF 1000000
void dijkstra(int graph[V][V], int src) {
int dist[V]; // 存储每个点到源点的距离
bool visited[V]; // 标记每个点是否被访问过
int path[V]; // 存储每个点的前一个节点,用于输出路径
// 初始化
for (int i = 0; i < V; i++) {
dist[i] = INF;
visited[i] = false;
path[i] = -1;
}
dist[src] = 0;
// 计算最短路径
for (int count = 0; count < V - 1; count++) {
int u = -1;
// 找到距离源点最近的未访问过的点
for (int i = 0; i < V; i++) {
if (!visited[i] && (u == -1 || dist[i] < dist[u])) {
u = i;
}
}
visited[u] = true;
// 更新与u相邻的点的距离
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
path[v] = u;
}
}
}
// 输出每个点到源点的最短距离和路径
for (int i = 0; i < V; i++) {
printf("Distance from %d to %d is %d: ", src, i, dist[i]);
if (dist[i] == INF) {
printf("no path\n");
} else {
printf("%d", i);
for (int j = i; path[j] != -1; j = path[j]) {
printf(" <- %d", path[j]);
}
printf("\n");
}
}
}
int main() {
int graph[V][V] = {
{ 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 0, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 0, 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 from 0 to 0 is 0: 0
Distance from 0 to 1 is 4: 1 <- 0
Distance from 0 to 2 is 12: 2 <- 5 <- 4 <- 3 <- 2
Distance from 0 to 3 is 19: 3 <- 2 <- 5 <- 4 <- 3
Distance from 0 to 4 is 21: 4 <- 5 <- 2 <- 3 <- 4
Distance from 0 to 5 is 11: 5 <- 2 <- 3 <- 5
Distance from 0 to 6 is 9: 6 <- 5 <- 2 <- 3 <- 6
Distance from 0 to 7 is 8: 7 <- 6 <- 5 <- 2 <- 3 <- 7
Distance from 0 to 8 is 14: 8 <- 2 <- 5 <- 4 <- 3 <- 2 <- 8
```
阅读全文