请用c语言编写Dijkstra算法求最短路径,要求可测试任意加权图
时间: 2024-03-10 21:49:16 浏览: 70
好的,我会用C语言编写Dijkstra算法求最短路径。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 1000
int graph[MAX_VERTICES][MAX_VERTICES];
int dist[MAX_VERTICES];
int visited[MAX_VERTICES];
int num_vertices;
int min_distance()
{
int min = INT_MAX, min_index, i;
for (i = 0; i < num_vertices; i++)
if (!visited[i] && dist[i] <= min)
min = dist[i], min_index = i;
return min_index;
}
void dijkstra(int src)
{
int i, count, u, v;
for (i = 0; i < num_vertices; i++)
dist[i] = INT_MAX, visited[i] = 0;
dist[src] = 0;
for (count = 0; count < num_vertices - 1; count++) {
u = min_distance();
visited[u] = 1;
for (v = 0; v < num_vertices; 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];
}
}
int main()
{
int i, j, src, dest;
printf("Enter the number of vertices: ");
scanf("%d", &num_vertices);
printf("Enter the graph (enter 0 if there is no edge):\n");
for (i = 0; i < num_vertices; i++)
for (j = 0; j < num_vertices; j++)
scanf("%d", &graph[i][j]);
printf("Enter the source vertex: ");
scanf("%d", &src);
dijkstra(src);
printf("\nShortest distances from vertex %d:\n", src);
for (i = 0; i < num_vertices; i++)
printf("%d to %d: %d\n", src, i, dist[i]);
return 0;
}
```
在这个实现中,我们使用了邻接矩阵来表示图,并使用了Dijkstra算法来计算最短路径。用户可以输入任意的加权图,程序会输出从指定源点到其他所有顶点的最短距离。
注意,这个实现中使用了标准库中的 `limits.h` 头文件,其中定义了整型变量的最大值和最小值。如果编译器不支持该头文件,需要手动定义这些值。
阅读全文