输入无向图的顶点数、边数及各条边的顶点对,建立用邻接表表示的无向图,对图进行深度优先搜索和广度优先搜索遍历,并分别输出其遍历序列。c语言
时间: 2024-02-03 22:15:22 浏览: 72
以下是使用邻接表表示无向图,实现深度优先搜索和广度优先搜索遍历的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
/* 邻接表结构体定义 */
typedef struct ArcNode {
int adjvex; // 相邻顶点编号
struct ArcNode* nextarc; // 指向下一个相邻顶点的指针
} ArcNode;
typedef struct VertexNode {
char data; // 顶点信息
ArcNode* firstarc; // 指向第一个相邻顶点的指针
} VertexNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices; // 邻接表
int vexnum, arcnum; // 顶点数和边数
} ALGraph;
/* 函数声明 */
void CreateGraph(ALGraph *G);
void DFS(ALGraph *G, int v, int *visited);
void DFSTraverse(ALGraph *G);
void BFS(ALGraph *G);
void BFSTraverse(ALGraph *G);
int main() {
ALGraph G;
CreateGraph(&G);
printf("DFS序列:");
DFSTraverse(&G);
printf("\nBFS序列:");
BFSTraverse(&G);
return 0;
}
/* 创建邻接表表示的无向图 */
void CreateGraph(ALGraph *G) {
printf("请输入顶点数和边数:");
scanf("%d%d", &G->vexnum, &G->arcnum);
fflush(stdin);
printf("请输入各顶点信息:\n");
for (int i = 0; i < G->vexnum; i++) {
scanf("%c", &G->vertices[i].data);
G->vertices[i].firstarc = NULL;
fflush(stdin);
}
printf("请输入各边的顶点对:\n");
for (int i = 0; i < G->arcnum; i++) {
int v1, v2;
scanf("%d%d", &v1, &v2);
fflush(stdin);
/* 添加边v1->v2 */
ArcNode* arc1 = (ArcNode*)malloc(sizeof(ArcNode));
arc1->adjvex = v2;
arc1->nextarc = G->vertices[v1].firstarc;
G->vertices[v1].firstarc = arc1;
/* 添加边v2->v1 */
ArcNode* arc2 = (ArcNode*)malloc(sizeof(ArcNode));
arc2->adjvex = v1;
arc2->nextarc = G->vertices[v2].firstarc;
G->vertices[v2].firstarc = arc2;
}
}
/* 深度优先搜索遍历 */
void DFS(ALGraph *G, int v, int *visited) {
printf("%c ", G->vertices[v].data);
visited[v] = 1;
ArcNode* arc = G->vertices[v].firstarc;
while (arc != NULL) {
int adjvex = arc->adjvex;
if (visited[adjvex] == 0) {
DFS(G, adjvex, visited);
}
arc = arc->nextarc;
}
}
void DFSTraverse(ALGraph *G) {
int visited[MAX_VERTEX_NUM] = {0};
for (int i = 0; i < G->vexnum; i++) {
if (visited[i] == 0) {
DFS(G, i, visited);
}
}
}
/* 广度优先搜索遍历 */
void BFS(ALGraph *G, int v, int *visited) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
printf("%c ", G->vertices[v].data);
visited[v] = 1;
queue[rear++] = v;
while (front < rear) {
int u = queue[front++];
ArcNode* arc = G->vertices[u].firstarc;
while (arc != NULL) {
int adjvex = arc->adjvex;
if (visited[adjvex] == 0) {
printf("%c ", G->vertices[adjvex].data);
visited[adjvex] = 1;
queue[rear++] = adjvex;
}
arc = arc->nextarc;
}
}
}
void BFSTraverse(ALGraph *G) {
int visited[MAX_VERTEX_NUM] = {0};
for (int i = 0; i < G->vexnum; i++) {
if (visited[i] == 0) {
BFS(G, i, visited);
}
}
}
```
使用示例:
```
请输入顶点数和边数:5 6
请输入各顶点信息:
a
b
c
d
e
请输入各边的顶点对:
0 1
0 2
1 2
1 3
2 3
3 4
DFS序列:a b c d e
BFS序列:a b c d e
```
阅读全文