编写c语言程序计算从“0”结点到其他结点的最短距离。
时间: 2024-02-12 14:03:00 浏览: 155
好的,这里提供一个使用 Dijkstra 算法求解单源最短路径的 C 语言程序,假设图以邻接表的形式存储:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define V 6 // 结点个数
// 邻接表结点
struct AdjListNode {
int dest; // 目标结点
int weight; // 边权重
struct AdjListNode* next;
};
// 邻接表
struct AdjList {
struct AdjListNode* head;
};
// 图结构体
struct Graph {
struct AdjList* array;
};
// 创建邻接表结点
struct AdjListNode* newAdjListNode(int dest, int weight) {
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
// 创建图
struct Graph* createGraph(int V) {
struct Graph* graph =
(struct Graph*) malloc(sizeof(struct Graph));
graph->array =
(struct AdjList*) malloc(V * sizeof(struct AdjList));
for (int i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
// 添加边
void addEdge(struct Graph* graph, int src, int dest, int weight) {
struct AdjListNode* newNode = newAdjListNode(dest, weight);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}
// 打印距离数组
void printDistances(int dist[]) {
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
// 找到距离最短的结点
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;
}
// 使用 Dijkstra 算法求解单源最短路径
void dijkstra(struct Graph* graph, 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;
struct AdjListNode* pCrawl = graph->array[u].head;
while (pCrawl != NULL) {
int v = pCrawl->dest;
if (!sptSet[v] && pCrawl->weight &&
dist[u] != INT_MAX && dist[u] + pCrawl->weight < dist[v])
dist[v] = dist[u] + pCrawl->weight;
pCrawl = pCrawl->next;
}
}
printDistances(dist);
}
// 测试
int main() {
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1, 5);
addEdge(graph, 0, 2, 3);
addEdge(graph, 1, 3, 6);
addEdge(graph, 1, 2, 2);
addEdge(graph, 2, 4, 4);
addEdge(graph, 2, 5, 2);
addEdge(graph, 2, 3, 7);
addEdge(graph, 3, 4, -1);
addEdge(graph, 4, 5, -2);
dijkstra(graph, 0);
return 0;
}
```
以上是一个简单的 Dijkstra 算法的实现,其中图的结构体使用邻接表存储,使用了一个 dist 数组来存储起点到各个结点的最短距离,使用了一个 sptSet 数组来判断结点是否已确定最短路径。在 main 函数中添加边后,调用 dijkstra 函数来计算最短路径。
阅读全文