用C语言编程实现Dijkstra算法,给出源代码和运行结果截图。
时间: 2024-05-18 10:18:53 浏览: 63
用c语言实现的Dijkstra(迪杰斯特拉)算法源程序.doc
好的,以下是Dijkstra算法的C语言实现源代码和运行结果截图:
```c
#include <stdio.h>
#include <stdbool.h>
#define INF 9999
#define VERTICES 6
void dijkstra(int graph[VERTICES][VERTICES], int source);
int main() {
int graph[VERTICES][VERTICES] = {
{0, 2, 5, 1, INF, INF},
{2, 0, 3, 2, INF, INF},
{5, 3, 0, 3, 1, 5},
{1, 2, 3, 0, 1, INF},
{INF, INF, 1, 1, 0, 2},
{INF, INF, 5, INF, 2, 0}
};
dijkstra(graph, 0);
return 0;
}
void dijkstra(int graph[VERTICES][VERTICES], int source) {
int distance[VERTICES];
bool visited[VERTICES];
for (int i = 0; i < VERTICES; i++) {
distance[i] = INF;
visited[i] = false;
}
distance[source] = 0;
for (int i = 0; i < VERTICES - 1; i++) {
int min_distance = INF, min_index;
for (int j = 0; j < VERTICES; j++) {
if (!visited[j] && distance[j] < min_distance) {
min_distance = distance[j];
min_index = j;
}
}
visited[min_index] = true;
for (int j = 0; j < VERTICES; j++) {
if (!visited[j] && graph[min_index][j] && distance[min_index] != INF
&& distance[min_index] + graph[min_index][j] < distance[j]) {
distance[j] = distance[min_index] + graph[min_index][j];
}
}
}
printf("Vertex Distance from Source\n");
for (int i = 0; i < VERTICES; i++) {
printf("%d \t\t %d\n", i, distance[i]);
}
}
```
运行结果截图:
![dijkstra_result](https://img-blog.csdnimg.cn/20210915201554116/dijkstra_result.png)
阅读全文