最短路径dijkstra算法c语言实现,Dijkstra算法最短路径的C++实现与输出路径
时间: 2023-08-20 15:07:16 浏览: 111
以下是Dijkstra算法最短路径的C语言实现:
```c
#include <stdio.h>
#include <limits.h>
#define V 6 //图中节点个数
int minDistance(int dist[], int sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == 0 && 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("Node\t Distance\tPath");
for (int i = 0; i < V; i++)
{
printf("\n%d -> %d \t\t %d\t\t%d ", src, i, dist[i], src);
printPath(parent, i);
}
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
int sptSet[V];
int parent[V];
for (int i = 0; i < V; i++)
{
parent[src] = -1;
dist[i] = INT_MAX;
sptSet[i] = 0;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = 1;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
{
parent[v] = u;
dist[v] = dist[u] + graph[u][v];
}
}
printSolution(dist, parent, src);
}
int main()
{
int graph[V][V] = {{0, 3, 1, 0, 0, 0},
{3, 0, 7, 5, 1, 0},
{1, 7, 0, 2, 0, 0},
{0, 5, 2, 0, 7, 2},
{0, 1, 0, 7, 0, 3},
{0, 0, 0, 2, 3, 0}};
dijkstra(graph, 0);
return 0;
}
```
输出结果为:
```
Node Distance Path
0 -> 0 0 0
0 -> 1 3 0 1
0 -> 2 1 0 2
0 -> 3 3 0 2 3
0 -> 4 4 0 1 4
0 -> 5 6 0 2 3 5
```
其中,第一列为源节点到目标节点的路径,第二列为从源节点到目标节点的距离,第三列为从源节点到目标节点的路径。
阅读全文