c语言实现求带权无向图中单源最短路径的迪克斯特拉算法的代码
时间: 2024-04-07 18:31:42 浏览: 29
以下是使用迪克斯特拉算法求解带权无向图中单源最短路径的 C 语言实现代码:
```c
#include <stdio.h>
#include <limits.h>
#define V 5 // 图中顶点数
int minDistance(int dist[], int sptSet[]) {
// 从尚未处理的顶点中找到距离最小的顶点
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (sptSet[v] == 0 && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printSolution(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
void dijkstra(int graph[V][V], int src) {
int dist[V]; // 存储从源点到各顶点的最短距离
int sptSet[V]; // 存储已处理的顶点
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
}
dist[src] = 0; // 源点到自己的距离为0
for (int count = 0; count < V-1; count++) {
int u = minDistance(dist, sptSet); // 从尚未处理的顶点中找到距离最小的顶点
sptSet[u] = 1; // 标记该顶点为已处理
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]+graph[u][v] < dist[v]) {
// 如果顶点未被处理且与 u 相连,且通过 u 到达 v 的距离更短,则更新距离
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist); // 打印最短路径
}
int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
dijkstra(graph, 0); // 计算从顶点0出发到其他各顶点的最短路径
return 0;
}
```
在上述代码中,我们首先定义了一个 `minDistance` 函数,用于从尚未处理的顶点中找到距离最小的顶点。然后定义了 `printSolution` 函数,用于打印最短路径。最后定义了 `dijkstra` 函数,用于计算从源点到各顶点的最短路径。在 `dijkstra` 函数中,我们首先初始化了 `dist` 数组和 `sptSet` 数组,然后进行循环处理,每次选择一个距离最小的顶点,并将其标记为已处理,然后更新与该顶点相连的其他顶点的距离。最后调用 `printSolution` 函数打印结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)