用c语言实现 Dijkstra (迪杰斯特拉) 算法
时间: 2023-09-22 22:07:41 浏览: 182
Dijkstra算法是一种用于求解最短路径的算法,以下是使用C语言实现的示例代码:
```c
#include <stdio.h>
#include <limits.h>
#define VERTICES 6
int minDistance(int dist[], int visited[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < VERTICES; v++) {
if (visited[v] == 0 && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void dijkstra(int graph[VERTICES][VERTICES], int start) {
int dist[VERTICES];
int visited[VERTICES];
for (int i = 0; i < VERTICES; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[start] = 0;
for (int count = 0; count < VERTICES - 1; count++) {
int u = minDistance(dist, visited);
visited[u] = 1;
for (int v = 0; v < 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];
}
}
}
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < VERTICES; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
int main() {
int graph[VERTICES][VERTICES] = {{0, 1, 4, 0, 0, 0},
{1, 0, 2, 5, 7, 0},
{4, 2, 0, 1, 0, 0},
{0, 5, 1, 0, 3, 8},
{0, 7, 0, 3, 0, 1},
{0, 0, 0, 8, 1, 0}};
dijkstra(graph, 0);
return 0;
}
```
在这个示例中,我们使用了邻接矩阵来表示图,其中`graph[i][j]`表示从顶点`i`到顶点`j`的边的权重。`dijkstra`函数实现了Dijkstra算法,其中`dist`数组存储从源顶点到每个顶点的距离,`visited`数组用于标记已经访问过的顶点。`minDistance`函数用于查找距离源顶点最近的未访问过的顶点,该顶点将会成为下一个被访问的顶点。最后,`main`函数中构建了一个示例图,并将源顶点设置为0,然后调用`dijkstra`函数来求解最短路径。
阅读全文