C语言编程一个狄克斯特拉算法求起始点到终点的最短距离和最短路径
时间: 2023-11-21 09:06:49 浏览: 75
狄克斯特拉算法(Dijkstra Algorithm)是一种用于求解带权图中单源最短路径的算法。下面是一个基于C语言的狄克斯特拉算法实现:
```c
#include<stdio.h>
#include<limits.h>
#define V 9
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, int dest)
{
printf("从%d到%d的最短距离为:%d\n", src, dest, dist[dest]);
printf("最短路径为:");
printPath(parent, dest);
printf("%d ", src);
}
void dijkstra(int graph[V][V], int src, int dest)
{
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, dest);
}
int main()
{
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
int src = 0, dest = 8;
dijkstra(graph, src, dest);
return 0;
}
```
上面代码中的图是一个9个顶点的图,可以根据实际需求修改。在这个例子中,图的顶点编号从0到8,0号顶点是起点,8号顶点是终点。运行程序后,会输出从起点到终点的最短距离和最短路径。
阅读全文