dijkstra滑行路径算法的C语言代码
时间: 2023-12-15 10:56:15 浏览: 64
下面是Dijkstra滑行路径算法的C语言代码:
```c
#include <stdio.h>
#include <limits.h>
#define ROW 5
#define COL 5
int graph[ROW][COL] = {
{0, 4, 0, 0, 0},
{4, 0, 8, 0, 0},
{0, 8, 0, 7, 0},
{0, 0, 7, 0, 9},
{0, 0, 0, 9, 0}
};
int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < ROW; v++)
if (sptSet[v] == 0 && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printSolution(int dist[]) {
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < ROW; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
void dijkstra(int src) {
int dist[ROW];
int sptSet[ROW];
for (int i = 0; i < ROW; i++)
dist[i] = INT_MAX, sptSet[i] = 0;
dist[src] = 0;
for (int count = 0; count < ROW - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = 1;
for (int v = 0; v < ROW; v++)
if (!sptSet[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() {
dijkstra(0);
return 0;
}
```
这里是一个简单的例子,表示从第一个顶点到其他所有顶点的最短路径。您可以根据自己的需求修改顶点和边的数量,以及图的结构。
阅读全文