用C语言构建无向网,并在此基础上求得指定起点和终点的最短路径,并且添加中文注释
时间: 2024-06-14 07:05:27 浏览: 87
基于C语言的最短路径算法
以下是用C语言构建无向网并求得指定起点和终点的最短路径的示例代码,同时添加了中文注释:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100 // 最大顶点数
// 无向网的邻接矩阵表示
typedef struct {
int matrix[MAX_VERTICES][MAX_VERTICES]; // 邻接矩阵
int numVertices; // 顶点数
} Graph;
// 初始化无向网
void initGraph(Graph *graph, int numVertices) {
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->matrix[i][j] = INT_MAX; // 初始化邻接矩阵中的元素为无穷大
}
}
}
// 添加边
void addEdge(Graph *graph, int start, int end, int weight) {
graph->matrix[start][end] = weight;
graph->matrix[end][start] = weight;
}
// Dijkstra算法求最短路径
void dijkstra(Graph *graph, int start, int end) {
int dist[MAX_VERTICES]; // 存储起点到各顶点的最短距离
int visited[MAX_VERTICES] = {0}; // 标记顶点是否已访问
int prev[MAX_VERTICES]; // 存储最短路径上的前驱顶点
// 初始化
for (int i = 0; i < graph->numVertices; i++) {
dist[i] = INT_MAX;
prev[i] = -1;
}
dist[start] = 0;
// 寻找最短路径
for (int i = 0; i < graph->numVertices; i++) {
int minDist = INT_MAX;
int minIndex = -1;
// 找到当前未访问的顶点中距离起点最近的顶点
for (int j = 0; j < graph->numVertices; j++) {
if (!visited[j] && dist[j] < minDist) {
minDist = dist[j];
minIndex = j;
}
}
if (minIndex == -1) {
break; // 所有顶点都已访问完毕
}
visited[minIndex] = 1; // 标记该顶点为已访问
// 更新与该顶点相邻的顶点的最短距离
for (int j = 0; j < graph->numVertices; j++) {
if (!visited[j] && graph->matrix[minIndex][j] != INT_MAX) {
int newDist = dist[minIndex] + graph->matrix[minIndex][j];
if (newDist < dist[j]) {
dist[j] = newDist;
prev[j] = minIndex;
}
}
}
}
// 输出最短路径
printf("从顶点%d到顶点%d的最短路径为:", start, end);
int path[MAX_VERTICES];
int pathLength = 0;
int current = end;
while (current != -1) {
path[pathLength++] = current;
current = prev[current];
}
for (int i = pathLength - 1; i >= 0; i--) {
printf("%d ", path[i]);
}
printf("\n最短路径长度为:%d\n", dist[end]);
}
int main() {
Graph graph;
int numVertices = 6; // 顶点数
initGraph(&graph, numVertices);
// 添加边
addEdge(&graph, 0, 1, 7);
addEdge(&graph, 0, 2, 9);
addEdge(&graph, 0, 5, 14);
addEdge(&graph, 1, 2, 10);
addEdge(&graph, 1, 3, 15);
addEdge(&graph, 2, 3, 11);
addEdge(&graph, 2, 5, 2);
addEdge(&graph, 3, 4, 6);
addEdge(&graph, 4, 5, 9);
int start = 0; // 起点
int end = 4; // 终点
dijkstra(&graph, start, end);
return 0;
}
```
阅读全文