dijkstra算法c语言最短路径
时间: 2023-11-25 19:07:43 浏览: 152
Dijkstra算法是一种用于计算图中单源最短路径的贪心算法。下面是Dijkstra算法的C语言实现过程:
1. 初始化:将源点s到各个顶点的距离dist数组初始化为无穷大,将源点s到自身的距离dist[s]初始化为0,将各个顶点的最短路径是否已经确定的标记数组final初始化为false。
2. 第一轮:找到dist数组中最小的值,将其对应的顶点标记为已确定最短路径final[v]=true,并更新源点s到其它顶点的距离dist数组。
3. 第二轮:重复第一轮的操作,找到dist数组中未被标记的最小值,将其对应的顶点标记为已确定最短路径final[v]=true,并更新源点s到其它顶点的距离dist数组。
4. 重复第二轮的操作,直到所有顶点的最短路径都已经确定。
下面是Dijkstra算法的C语言代码实现:
```c
#include <stdio.h>
#include <limits.h>
#define V 6 // 图的顶点数
int minDistance(int dist[], bool final[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (final[v] == false && 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 %d\n", i, dist[i]);
}
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool final[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
final[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, final);
final[u] = true;
for (int v = 0; v < V; v++) {
if (!final[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, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0}};
dijkstra(graph, 0);
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)