用C语言编程实现Dijkstra算法
时间: 2023-08-12 17:07:45 浏览: 97
c语言实现dijkstra算法
好的,下面是用C语言编写的Dijkstra算法的代码实现:
```c
#include <stdio.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 printSolution(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
void dijkstra(int graph[V][V], int src) {
int dist[V]; // 存储从源点到各个顶点的最短距离
int visited[V]; // 标记各个顶点是否已经被访问过
// 初始化
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[src] = 0;
// 计算最短路径
for (int count = 0; count < V - 1; count++) {
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];
}
}
}
printSolution(dist);
}
int main() {
int graph[V][V] = {
{0, 2, 5, 0, 0, 0},
{2, 0, 4, 6, 0, 0},
{5, 4, 0, 1, 5, 0},
{0, 6, 1, 0, 3, 6},
{0, 0, 5, 3, 0, 2},
{0, 0, 0, 6, 2, 0}
};
dijkstra(graph, 0);
return 0;
}
```
该代码实现了Dijkstra算法,计算了从源点0到其他各个顶点的最短距离,并将结果输出到控制台上。
阅读全文