迪杰斯特拉算法的c语言实现
时间: 2023-06-19 14:07:46 浏览: 98
以下是迪杰斯特拉算法的C语言实现,其中包含了注释以便理解:
```c
#include <stdio.h>
#include <limits.h>
#define V 9 // 定义顶点个数
int minDistance(int dist[], bool sptSet[]) { // 找到最短距离的顶点
int min = INT_MAX, min_index; // 初始化最小值和最小值对应的顶点
for (int v = 0; v < V; v++)
if (sptSet[v] == false && 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]; // 存储起点到各个顶点的最短距离
bool sptSet[V]; // 存储各个顶点是否已经求得最短距离
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false; // 初始化
dist[src] = 0; // 起点到自己的距离为0
for (int count = 0; count < V - 1; count++) { // 遍历除了起点以外的所有顶点
int u = minDistance(dist, sptSet); // 找到未求得最短距离的顶点中距离最小的顶点
sptSet[u] = true; // 将该顶点标记为已求得最短距离
for (int v = 0; v < V; v++) // 更新其他顶点的最短距离
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist); // 打印结果
}
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, 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); // 计算起点为0的最短距离
return 0;
}
```
以上代码实现了一个带有9个顶点的图,并计算了起点为0的最短距离。你可以根据自己的需求修改顶点个数和图的内容。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)