请帮我写一个使用dijkstra算法解决最简单最短路径的c语言程序
时间: 2024-11-09 22:30:07 浏览: 7
Dijkstra算法是一种用于寻找图中两点之间最短路径的经典算法,通常用于有向无环图(DAG)和加权边的情况。下面是一个简单的Dijkstra算法的C语言实现示例:
```c
#include <stdio.h>
#include <limits.h>
#define V 9 // 图的顶点数
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, 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;
}
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // 存储最短距离
bool sptSet[V]; // 标记已找到最短路径的顶点
// 初始化所有顶点的距离和标记
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];
}
}
// 打印结果
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
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); // 从源节点0开始搜索
return 0;
}
阅读全文