用dijkstra算法求最短路径问题,输入顶点数,输入权值,输入出发顶点,输出最短路径,C语言
时间: 2023-08-14 12:02:41 浏览: 68
下面是使用Dijkstra算法求解最短路径问题的C语言代码:
```c
#include <stdio.h>
#include <limits.h>
#define MAX_VERTICES 100
// 表示无穷大的值
#define INFINITY INT_MAX
// 存储图中的边
typedef struct {
int start_vertex;
int end_vertex;
int weight;
} Edge;
// 存储图的结构体
typedef struct {
int num_vertices; // 图中顶点的数量
int num_edges; // 图中边的数量
Edge edges[MAX_VERTICES * (MAX_VERTICES - 1) / 2]; // 存储图中的边
} Graph;
// 计算从起点到各个顶点的最短路径
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int num_vertices, int start, int dist[]) {
int visited[MAX_VERTICES] = {0}; // 标记是否已访问过该顶点
int i, j, k, min_dist;
// 初始化距离数组
for (i = 0; i < num_vertices; i++) {
dist[i] = INFINITY;
}
dist[start] = 0; // 起点到起点的距离为0
// 计算从起点到各个顶点的最短路径
for (i = 0; i < num_vertices-1; i++) {
// 找到当前未访问过的距离起点最近的顶点
min_dist = INFINITY;
for (j = 0; j < num_vertices; j++) {
if (!visited[j] && dist[j] < min_dist) {
k = j;
min_dist = dist[j];
}
}
// 标记该顶点已被访问
visited[k] = 1;
// 更新与该顶点相邻的顶点的距离
for (j = 0; j < num_vertices; j++) {
if (graph[k][j] != 0 && (dist[k] + graph[k][j] < dist[j])) {
dist[j] = dist[k] + graph[k][j];
}
}
}
}
int main() {
Graph g;
int graph[MAX_VERTICES][MAX_VERTICES]; // 存储图的邻接矩阵
int num_vertices, num_edges, start_vertex, i, j;
int dist[MAX_VERTICES]; // 存储最短路径
// 读入图的顶点数和边数
printf("Enter the number of vertices:");
scanf("%d", &num_vertices);
printf("Enter the number of edges:");
scanf("%d", &num_edges);
// 读入每条边的起点、终点和权值
for (i = 0; i < num_edges; i++) {
printf("Enter the start vertex, end vertex and weight of edge %d:", i+1);
scanf("%d %d %d", &g.edges[i].start_vertex, &g.edges[i].end_vertex, &g.edges[i].weight);
}
// 构建邻接矩阵
for (i = 0; i < num_vertices; i++) {
for (j = 0; j < num_vertices; j++) {
graph[i][j] = 0;
}
}
for (i = 0; i < num_edges; i++) {
graph[g.edges[i].start_vertex-1][g.edges[i].end_vertex-1] = g.edges[i].weight;
}
// 读入起点
printf("Enter the start vertex:");
scanf("%d", &start_vertex);
// 计算最短路径
dijkstra(graph, num_vertices, start_vertex-1, dist);
// 输出最短路径
printf("The shortest path from %d to each vertex is:\n", start_vertex);
for (i = 0; i < num_vertices; i++) {
printf("Vertex %d: ", i+1);
if (dist[i] == INFINITY) {
printf("There is no path from %d to %d.\n", start_vertex, i+1);
} else {
printf("%d\n", dist[i]);
}
}
return 0;
}
```
在这个程序中,我们首先读入图的顶点数和边数,然后读入每条边的起点、终点和权值,并利用这些信息构建出图的邻接矩阵。
接着,我们读入起点,并使用Dijkstra算法计算从起点到各个顶点的最短路径。最后,我们输出最短路径。
阅读全文