给我一个C语言写的用邻接表求最短路径的示例
时间: 2024-05-13 10:16:01 浏览: 106
好的,下面是一个用邻接表求最短路径的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXV 1000
#define INF 0x3f3f3f3f
typedef struct EdgeNode { // 邻接表中边的结构体
int adjvex; // 邻接顶点编号
int weight; // 边的权值
struct EdgeNode *next; // 指向下一条边的指针
} EdgeNode;
typedef struct VertexNode { // 邻接表中顶点的结构体
int data; // 顶点数据
EdgeNode *firstedge; // 指向第一条边的指针
} VertexNode;
typedef struct Graph { // 邻接表表示的图
VertexNode vertex[MAXV];
int n, e; // 顶点数和边数
} Graph;
typedef struct ShortestPath { // 存储最短路径和路径长度
int path[MAXV];
int dist[MAXV];
} ShortestPath;
void CreateGraph(Graph *G) { // 创建图
printf("输入顶点数和边数:");
scanf("%d %d", &G->n, &G->e);
printf("输入各顶点的数据:");
for (int i = 0; i < G->n; i++) {
scanf("%d", &G->vertex[i].data);
G->vertex[i].firstedge = NULL;
}
for (int i = 0; i < G->e; i++) {
int u, v, w;
printf("输入边(u, v)的顶点编号和权值:");
scanf("%d %d %d", &u, &v, &w);
EdgeNode *e1 = (EdgeNode *)malloc(sizeof(EdgeNode));
e1->adjvex = v;
e1->weight = w;
e1->next = G->vertex[u].firstedge;
G->vertex[u].firstedge = e1;
EdgeNode *e2 = (EdgeNode *)malloc(sizeof(EdgeNode));
e2->adjvex = u;
e2->weight = w;
e2->next = G->vertex[v].firstedge;
G->vertex[v].firstedge = e2;
}
}
void Dijkstra(Graph *G, int start, ShortestPath *S) { // Dijkstra算法求最短路径
int vis[MAXV] = {0}; // 判断该点是否已确定最短路径
for (int i = 0; i < G->n; i++) {
S->path[i] = -1; // 初始化路径
S->dist[i] = INF; // 初始化路径长度
}
S->path[start] = start;
S->dist[start] = 0;
vis[start] = 1; // 起点已确定最短路径
EdgeNode *p = G->vertex[start].firstedge;
while (p) { // 更新起点相邻点的路径长度
S->dist[p->adjvex] = p->weight;
S->path[p->adjvex] = start;
p = p->next;
}
for (int i = 1; i < G->n; i++) { // 依次确定剩余的点的最短路径
int min_dist = INF;
int u;
for (int j = 0; j < G->n; j++) { // 找到未确定最短路径的点中距离起点最近的点
if (!vis[j] && S->dist[j] < min_dist) {
u = j;
min_dist = S->dist[j];
}
}
vis[u] = 1;
p = G->vertex[u].firstedge;
while (p) { // 更新新确定最短路径的点相邻点的路径长度
if (!vis[p->adjvex] && S->dist[p->adjvex] > S->dist[u] + p->weight) {
S->dist[p->adjvex] = S->dist[u] + p->weight;
S->path[p->adjvex] = u;
}
p = p->next;
}
}
}
int main() {
Graph G;
ShortestPath S;
CreateGraph(&G);
Dijkstra(&G, 0, &S);
printf("最短路径长度:\n");
for (int i = 0; i < G.n; i++) {
printf("%d ", S.dist[i]);
}
printf("\n最短路径:\n");
for (int i = 0; i < G.n; i++) {
printf("%d ", S.path[i]);
}
return 0;
}
```
这个示例程序使用了 Dijkstra 算法求最短路径,实现了一个邻接表表示的图,并且输出了最短路径长度和路径。你可以根据自己的需要修改这个示例程序,来适应你的具体需求。
阅读全文