C语言如何用邻接矩阵的存储形式实现广度优先遍历查找最短路径长度,用代码显示出来
时间: 2024-04-29 16:25:33 浏览: 83
邻接矩阵存储图的深度优先遍历的代码实现
5星 · 资源好评率100%
以下是用邻接矩阵实现广度优先遍历查找最短路径长度的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 存储顶点信息
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 存储边信息
int vertex_num; // 顶点数
int edge_num; // 边数
} Graph;
// 初始化图
void init_graph(Graph* g) {
int i, j;
g->vertex_num = 0;
g->edge_num = 0;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
g->vertex[i] = 0;
for (j = 0; j < MAX_VERTEX_NUM; j++) {
g->edge[i][j] = 0;
}
}
}
// 添加顶点
void add_vertex(Graph* g, int v) {
g->vertex[g->vertex_num++] = v;
}
// 添加边
void add_edge(Graph* g, int v1, int v2, int weight) {
g->edge[v1][v2] = weight;
g->edge_num++;
}
// 广度优先遍历查找最短路径长度
int bfs(Graph* g, int start, int end) {
bool visited[MAX_VERTEX_NUM] = {false};
int queue[MAX_VERTEX_NUM] = {0};
int distance[MAX_VERTEX_NUM] = {0}; // 存储距离
int front = 0, rear = 0; // 队列头和尾指针
int i, v;
queue[rear++] = start;
visited[start] = true;
while (front < rear) {
v = queue[front++];
for (i = 0; i < g->vertex_num; i++) {
if (g->edge[v][i] != 0 && !visited[i]) {
visited[i] = true;
distance[i] = distance[v] + 1; // 距离是父节点距离加1
if (i == end) {
return distance[i]; // 找到目标节点,返回距离
}
queue[rear++] = i;
}
}
}
return -1; // 没有找到目标节点,返回-1
}
int main() {
Graph g;
init_graph(&g);
int i, start, end, weight;
printf("请输入顶点数:");
scanf("%d", &g.vertex_num);
printf("请输入边数:");
scanf("%d", &g.edge_num);
printf("请输入顶点信息:");
for (i = 0; i < g.vertex_num; i++) {
scanf("%d", &g.vertex[i]);
}
printf("请输入边信息:");
for (i = 0; i < g.edge_num; i++) {
int v1, v2;
printf("请输入第%d条边的起点和终点:", i + 1);
scanf("%d%d", &v1, &v2);
printf("请输入第%d条边的权重:", i + 1);
scanf("%d", &weight);
add_edge(&g, v1, v2, weight);
}
printf("请输入起点和终点:");
scanf("%d%d", &start, &end);
int distance = bfs(&g, start, end);
if (distance == -1) {
printf("没有找到路径!\n");
} else {
printf("最短路径长度为:%d\n", distance);
}
return 0;
}
```
阅读全文