单元最短路径算法代码c
时间: 2023-12-27 11:00:50 浏览: 77
单元最短路径算法(Dijkstra算法)是一种用于计算图中最短路径的算法。下面是用C语言编写的Dijkstra算法代码示例:
```c
#include <stdio.h>
#define INF 99999
void dijkstra(int graph[ ][ ], int n, int start) {
int cost[n][n], distance[n], pred[n];
int visited[n], count, mindistance, nextnode, i, j;
// 初始化
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(graph[i][j] == 0)
cost[i][j] = INF;
else
cost[i][j] = graph[i][j];
}
}
for(i = 0; i < n; i++) {
distance[i] = cost[start][i];
pred[i] = start;
visited[i] = 0;
}
distance[start] = 0;
visited[start] = 1;
count = 1;
while(count < n - 1) {
mindistance = INF;
// 找到下一个最短距离的节点
for(i = 0; i < n; i++) {
if(distance[i] < mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}
}
visited[nextnode] = 1;
// 更新距离数组
for(i = 0; i < n; i++) {
if(!visited[i]) {
if(mindistance + cost[nextnode][i] < distance[i]) {
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
}
}
count++;
}
// 输出最短路径和距离
for(i = 0; i < n; i++) {
if(i != start) {
printf("\n距离节点 %d 的最短路径 = %d", i, distance[i]);
printf("\n最短路径 = %d", i);
j = i;
do {
j = pred[j];
printf("<-%d", j);
}while(j != start);
}
}
}
int main() {
int graph[5][5] = {{0, 10, 0, 30, 100},
{10, 0, 50, 0, 0},
{0, 50, 0, 20, 10},
{30, 0, 20, 0, 60},
{100, 0, 10, 60, 0}};
int n = 5, start = 0;
dijkstra(graph, n, start);
return 0;
}
```
这个代码示例中包括了Dijkstra算法的实现,主要是通过使用邻接矩阵来表示图,并利用循环来更新最短路径和距离数组。最后输出了每个节点到起点的最短路径及其距离。
阅读全文