c语言中根据Dijkstra算法,实现求最短路径并输出最短路径的代码
时间: 2024-03-16 17:46:32 浏览: 71
以下是基于Dijkstra算法的C语言代码实现,可以求解最短路径并输出该路径:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
#define INF INT_MAX
typedef struct Graph {
int num_vertices;
int adj_mat[MAX_VERTICES][MAX_VERTICES];
} Graph;
int get_min_distance(int dist[], int visited[], int num_vertices) {
int min_dist = INF, min_index = -1;
for (int i = 0; i < num_vertices; i++) {
if (!visited[i] && dist[i] <= min_dist) {
min_dist = dist[i];
min_index = i;
}
}
return min_index;
}
void dijkstra(Graph *graph, int start) {
int dist[MAX_VERTICES];
int visited[MAX_VERTICES];
int prev[MAX_VERTICES];
for (int i = 0; i < graph->num_vertices; i++) {
dist[i] = INF;
visited[i] = 0;
prev[i] = -1;
}
dist[start] = 0;
for (int i = 0; i < graph->num_vertices - 1; i++) {
int u = get_min_distance(dist, visited, graph->num_vertices);
visited[u] = 1;
for (int v = 0; v < graph->num_vertices; v++) {
if (graph->adj_mat[u][v] && !visited[v] && dist[u] != INF && dist[u] + graph->adj_mat[u][v] < dist[v]) {
dist[v] = dist[u] + graph->adj_mat[u][v];
prev[v] = u;
}
}
}
printf("最短路径:\n");
for (int i = 0; i < graph->num_vertices; i++) {
if (i != start) {
printf("节点%d到节点%d的最短路径为:", start, i);
int path[MAX_VERTICES], path_len = 0;
int j = i;
while (prev[j] != -1) {
path[path_len++] = j;
j = prev[j];
}
path[path_len++] = j;
for (int k = path_len - 1; k >= 0; k--) {
printf("%d ", path[k]);
}
printf(",路径长度为:%d\n", dist[i]);
}
}
}
int main() {
Graph graph = {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}
}};
dijkstra(&graph, 0);
return 0;
}
```
这里的示例图采用邻接矩阵表示,可以根据需要进行修改。
阅读全文