Dijkstra算法求有向图的最短路径的c语言代码
时间: 2023-11-12 14:06:53 浏览: 103
请看下面的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_NODES 100
int costs[MAX_NODES][MAX_NODES]; // 记录边的权值
int dist[MAX_NODES]; // 记录最短路径长度
int visited[MAX_NODES] = {0}; // 标记此节点是否被访问过
int predecessor[MAX_NODES]; // 记录每个节点的前驱节点
int min_distance(int n) // 从未访问过的节点中找到最短距离的节点
{
int min_dist = INT_MAX;
int min_index = -1;
int i;
for (i = 0; i < n; i++)
if (!visited[i] && dist[i] < min_dist)
{
min_dist = dist[i];
min_index = i;
}
return min_index;
}
void dijkstra(int start_node, int n)
{
int i, cur_node;
for (i = 0; i < n; i++)
{
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[start_node] = 0;
predecessor[start_node] = -1;
for (i = 0; i < n-1; i++) // 迭代n-1次
{
cur_node = min_distance(n); // 获取距离源点最近的未访问过的节点
visited[cur_node] = 1; // 标记为已访问
int j;
for (j = 0; j < n; j++) // 更新与当前节点相邻的节点的距离
if (!visited[j] && costs[cur_node][j] && dist[cur_node] != INT_MAX &&
dist[cur_node]+costs[cur_node][j] < dist[j])
{
dist[j] = dist[cur_node] + costs[cur_node][j];
predecessor[j] = cur_node;
}
}
}
int main()
{
int num_of_nodes, start_node, end_node, i, j;
printf("请输入节点数:");
scanf("%d", &num_of_nodes);
printf("请输入节点之间的边以及权值,0代表不连通:\n");
for (i = 0; i < num_of_nodes; i++)
for (j = 0; j < num_of_nodes; j++)
scanf("%d", &costs[i][j]);
printf("请输入起点:");
scanf("%d", &start_node);
printf("请输入终点:");
scanf("%d", &end_node);
dijkstra(start_node, num_of_nodes);
printf("从起点%d到终点%d的最短路径长度为:%d\n", start_node, end_node, dist[end_node]);
printf("最短路径为:\n");
int path[MAX_NODES], path_length = 0;
i = end_node;
while (i != -1)
{
path[path_length++] = i;
i = predecessor[i];
}
for (i = path_length-1; i >= 0; i--)
printf("%d ", path[i]);
return 0;
}
```
阅读全文