找出所有最短路径代码c语言
时间: 2024-09-28 16:13:34 浏览: 35
弗洛伊德算法代码 C语言 示例及讲解
在C语言中,寻找图的最短路径通常会使用Dijkstra算法或者Floyd-Warshall算法。以下是使用Dijkstra算法的一个基本示例,它适用于非负权重的有向或无向图:
```c
#include <stdio.h>
#include <limits.h>
#define V 9
// 边结构体
typedef struct Edge {
int src, dest, weight;
} Edge;
// Dijkstra函数实现
void dijkstra(int graph[V][V], int src) {
int dist[V]; // 存储每个顶点到源的距离
bool visited[V] = {false}; // 标记已访问的节点
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX; // 初始化所有距离为无穷大
}
dist[src] = 0; // 源点到自身的距离设为0
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, visited);
visited[u] = true; // 标记当前最小距离的节点已访问
// 更新与其相邻未访问节点的距离
for (int v = 0; v < V; 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("Shortest path from %d to all vertices:\n", src);
for (int i = 0; i < V; i++) {
printf("%d -> %d: %d\n", src, i, dist[i]);
}
}
// 辅助函数找到最小距离的节点
int minDistance(int dist[], bool visited[]) {
int min_val = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] <= min_val)
min_val = dist[v], min_index = v;
}
return min_index;
}
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;
}
阅读全文