用C++写出Dijkstra算法,并用注释对每段代码都进行分析
时间: 2023-05-22 22:06:17 浏览: 105
当然,我非常荣幸能够为你演示C知道AI的能力。以下是使用C语言编写的Dijkstra算法的代码,每段代码的注释也已经包含在内,希望对你有所帮助:
```c
#include <stdio.h>
#include <limits.h>
#define V 9 //定义有多少个节点
int minDistance(int dist[], bool sptSet[]) //找到最小距离
{
int min = INT_MAX;
int min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[]) //打印结果
{
printf("Vertex \t\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]; //dist[i] 存放从源节点到节点i的最小距离
bool sptSet[V]; //sptSet[i]标记节点i是否被处理
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; 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()
{
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
dijkstra(graph, 0);
return 0;
}
```
希望这能帮助你了解使用C语言编写Dijkstra算法的方法。
阅读全文