设计一个校园以江西财经大学麦庐园为例导航系统要求实现输入所在地和目的地运用迪杰斯特拉算法编写一个C语言代码
以下是一个用C语言实现的校园导航系统示例代码,使用了Dijkstra算法来计算最短路径。
#include <stdio.h>
#include <stdbool.h>
#define MAX_VERTICES 100
#define INF 99999
typedef struct {
int cost;
bool visited;
int prev;
} Vertex;
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int source, int destination, int num_vertices) {
Vertex vertices[MAX_VERTICES];
// 初始化顶点信息
for (int i = 0; i < num_vertices; i++) {
vertices[i].cost = INF;
vertices[i].visited = false;
vertices[i].prev = -1;
}
vertices[source].cost = 0;
// 寻找最短路径
for (int i = 0; i < num_vertices; i++) {
int min_cost = INF;
int min_vertex = -1;
// 选择未访问的顶点中具有最小cost的顶点
for (int j = 0; j < num_vertices; j++) {
if (!vertices[j].visited && vertices[j].cost < min_cost) {
min_cost = vertices[j].cost;
min_vertex = j;
}
}
if (min_vertex == -1) {
break;
}
vertices[min_vertex].visited = true;
// 更新与min_vertex相邻的顶点的cost
for (int j = 0; j < num_vertices; j++) {
if (graph[min_vertex][j] > 0 && !vertices[j].visited) {
int new_cost = vertices[min_vertex].cost + graph[min_vertex][j];
if (new_cost < vertices[j].cost) {
vertices[j].cost = new_cost;
vertices[j].prev = min_vertex;
}
}
}
}
// 打印最短路径
int current_vertex = destination;
while (current_vertex != -1) {
printf("%d ", current_vertex);
current_vertex = vertices[current_vertex].prev;
}
}
int main() {
// 校园地图的邻接矩阵表示
int graph[MAX_VERTICES][MAX_VERTICES] = {
{0, 1, 2, 0, 0, 0},
{1, 0, 0, 4, 0, 0},
{2, 0, 0, 3, 4, 0},
{0, 4, 3, 0, 5, 6},
{0, 0, 4, 5, 0, 0},
{0, 0, 0, 6, 0, 0}
};
int num_vertices = 6;
int source, destination;
printf("请输入起始地点和目的地:");
scanf("%d %d", &source, &destination);
printf("最短路径为:");
dijkstra(graph, source, destination, num_vertices);
return 0;
}
这个示例代码使用邻接矩阵表示校园地图,其中的数字表示两个地点之间的距离。你可以根据实际情况修改邻接矩阵和顶点数量。用户需要输入起始地点和目的地,程序将根据Dijkstra算法计算出最短路径并打印出来
原文地址: http://www.cveoy.top/t/topic/h0TD 著作权归作者所有。请勿转载和采集!