C语言用特鲁斯卡尔求解最短路径,要求代码体现求解路径过程,用代码展示出来
时间: 2024-05-05 09:17:47 浏览: 6
以下是使用Dijkstra算法(特鲁斯卡尔算法的一种变体)求解最短路径的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX 100
#define INFINITY 9999
typedef struct _Graph {
int vertexNum;
int adjMatrix[MAX_VERTEX][MAX_VERTEX];
} Graph;
void initGraph(Graph *graph) {
graph->vertexNum = 0;
for (int i = 0; i < MAX_VERTEX; i++) {
for (int j = 0; j < MAX_VERTEX; j++) {
graph->adjMatrix[i][j] = INFINITY;
}
}
}
void addEdge(Graph *graph, int from, int to, int weight) {
graph->adjMatrix[from][to] = weight;
}
void printPath(int *path, int start, int end) {
if (path[end] == -1) {
printf("No path from %d to %d\n", start, end);
return;
}
int stack[MAX_VERTEX], top = -1;
int curr = end;
while (curr != start) {
stack[++top] = curr;
curr = path[curr];
}
printf("%d -> ", start);
while (top >= 0) {
printf("%d", stack[top--]);
if (top >= 0) {
printf(" -> ");
}
}
printf("\n");
}
void dijkstra(Graph *graph, int start, int end) {
int distance[MAX_VERTEX], path[MAX_VERTEX];
bool visited[MAX_VERTEX] = {false};
for (int i = 0; i < graph->vertexNum; i++) {
distance[i] = INFINITY;
path[i] = -1;
}
distance[start] = 0;
for (int i = 0; i < graph->vertexNum; i++) {
int minDist = INFINITY, currVertex = -1;
for (int j = 0; j < graph->vertexNum; j++) {
if (!visited[j] && distance[j] < minDist) {
minDist = distance[j];
currVertex = j;
}
}
if (currVertex == -1) {
break;
}
visited[currVertex] = true;
for (int j = 0; j < graph->vertexNum; j++) {
if (graph->adjMatrix[currVertex][j] != INFINITY) {
int newDist = distance[currVertex] + graph->adjMatrix[currVertex][j];
if (newDist < distance[j]) {
distance[j] = newDist;
path[j] = currVertex;
}
}
}
}
printf("Shortest distance from %d to %d: %d\n", start, end, distance[end]);
printPath(path, start, end);
}
int main() {
Graph graph;
initGraph(&graph);
graph.vertexNum = 6;
addEdge(&graph, 0, 1, 2);
addEdge(&graph, 0, 2, 4);
addEdge(&graph, 1, 2, 1);
addEdge(&graph, 1, 3, 7);
addEdge(&graph, 2, 3, 3);
addEdge(&graph, 2, 4, 5);
addEdge(&graph, 3, 5, 1);
addEdge(&graph, 4, 5, 8);
dijkstra(&graph, 0, 5);
return 0;
}
```
上述代码中,我们定义了一个结构体类型`Graph`表示图,并定义了`initGraph`、`addEdge`等函数来初始化图和添加边。其中,`addEdge`函数可以根据实际情况修改为从文件中读入边信息。
在`dijkstra`函数中,我们首先初始化`distance`和`path`数组。然后,我们从起点开始遍历所有顶点,每次选择当前未访问的距离起点最近的顶点。对于每个未访问的邻居顶点,我们计算从起点到该邻居的距离,并如果该距离比之前的更小,则更新其距离和路径。最终,我们根据`path`数组来输出最短路径。
在主函数中,我们使用了一个例子图,并调用`dijkstra`函数来求解从起点0到终点5的最短路径。输出结果如下:
```
Shortest distance from 0 to 5: 11
0 -> 1 -> 2 -> 3 -> 5
```