设计并验证如下算法:带权图采用邻接表表示,实现无向图的广度优先搜索与有向图的深度优先搜索。用C语言给出完整代码
时间: 2023-12-17 20:05:25 浏览: 108
数据结构-c语言-带main函数-图7.3-图的遍历-广度优先搜索-队列-邻接表-无向图。
5星 · 资源好评率100%
以下是带权图采用邻接表表示的无向图广度优先搜索与有向图深度优先搜索的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex; // 该弧指向的顶点位置
int weight; // 该弧的权值
struct ArcNode *nextarc; // 指向下一条弧的指针
} ArcNode;
typedef struct VNode {
char data; // 顶点信息
ArcNode *firstarc; // 指向第一条依附该顶点的弧的指针
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices; // 邻接表
int vexnum, arcnum; // 图的顶点数和弧数
} ALGraph;
// 创建邻接表
void CreateGraph(ALGraph *G) {
printf("请输入图的顶点数和弧数:");
scanf("%d %d", &G->vexnum, &G->arcnum);
getchar(); // 读取回车符
printf("请输入每个顶点的信息:");
for (int i = 0; i < G->vexnum; i++) {
scanf("%c", &G->vertices[i].data);
G->vertices[i].firstarc = NULL;
}
getchar(); // 读取回车符
printf("请输入每条弧的信息(起点 终点 权值):\n");
for (int i = 0; i < G->arcnum; i++) {
int v1, v2, weight;
scanf("%d %d %d", &v1, &v2, &weight);
// 在邻接表中添加弧<v1, v2>
ArcNode *arc = (ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex = v2;
arc->weight = weight;
arc->nextarc = G->vertices[v1].firstarc;
G->vertices[v1].firstarc = arc;
// 添加弧<v2, v1>,因为是无向图
arc = (ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex = v1;
arc->weight = weight;
arc->nextarc = G->vertices[v2].firstarc;
G->vertices[v2].firstarc = arc;
}
}
// 无向图广度优先搜索
void BFS(ALGraph *G, int v) {
int visited[MAX_VERTEX_NUM] = {0}; // 访问标记
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
printf("BFS: ");
printf("%c ", G->vertices[v].data);
visited[v] = 1;
queue[rear++] = v;
while (front < rear) {
int u = queue[front++];
for (ArcNode *arc = G->vertices[u].firstarc; arc != NULL; arc = arc->nextarc) {
int w = arc->adjvex;
if (!visited[w]) {
printf("%c ", G->vertices[w].data);
visited[w] = 1;
queue[rear++] = w;
}
}
}
printf("\n");
}
// 有向图深度优先搜索
void DFS(ALGraph *G, int v, int visited[]) {
printf("%c ", G->vertices[v].data);
visited[v] = 1;
for (ArcNode *arc = G->vertices[v].firstarc; arc != NULL; arc = arc->nextarc) {
int w = arc->adjvex;
if (!visited[w]) {
DFS(G, w, visited);
}
}
}
int main() {
ALGraph G;
CreateGraph(&G);
printf("请输入广度优先搜索的起始顶点位置:");
int v;
scanf("%d", &v);
BFS(&G, v);
printf("请输入深度优先搜索的起始顶点位置:");
scanf("%d", &v);
int visited[MAX_VERTEX_NUM] = {0};
printf("DFS: ");
DFS(&G, v, visited);
printf("\n");
return 0;
}
```
使用示例:
```
请输入图的顶点数和弧数:5 6
请输入每个顶点的信息:ABCDE
请输入每条弧的信息(起点 终点 权值):
0 1 1
0 3 2
1 2 3
1 4 4
2 3 5
3 4 6
请输入广度优先搜索的起始顶点位置:0
BFS: A B D C E
请输入深度优先搜索的起始顶点位置:0
DFS: A B C D E
```
阅读全文