C语言实现dijkstra最短路径算法打印路径
时间: 2023-10-16 12:11:44 浏览: 94
Dijkstra算法是一种经典的单源最短路径算法,以下是C语言实现Dijkstra算法并打印路径的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define V 6 // 图的顶点个数
int minDistance(int dist[], int visited[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printPath(int parent[], int j) {
if (parent[j] == -1)
return;
printPath(parent, parent[j]);
printf("%d ", j);
}
void printSolution(int dist[], int parent[], int src) {
printf("Vertex\t Distance\t Path\n");
for (int i = 0; i < V; i++) {
if (i != src) {
printf("%d -> %d\t %d\t\t %d ", src, i, dist[i], src);
printPath(parent, i);
printf("\n");
}
}
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
int visited[V];
int parent[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
parent[i] = -1;
}
dist[src] = 0;
for (int i = 0; i < V - 1; i++) {
int u = minDistance(dist, visited);
visited[u] = 1;
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u;
}
}
}
printSolution(dist, parent, src);
}
int main() {
int graph[V][V] = {{0, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0}};
dijkstra(graph, 0);
return 0;
}
```
该示例代码使用邻接矩阵存储图,并以0号顶点作为源点。运行该代码,将输出每个顶点到源点的最短距离和路径。
阅读全文