建立的无向图,实现图的深度优先遍历和广度优先遍历,并输出相应遍历结果用C语言,给一个使用示例
时间: 2023-09-10 14:15:28 浏览: 77
无向图建立、深度优先遍历和广度优先遍历实现算法[借鉴].pdf
5星 · 资源好评率100%
以下是一个简单的使用示例,实现图的深度优先遍历和广度优先遍历,并输出相应遍历结果:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100
// 边表结点
typedef struct ArcNode {
int adjvex; // 邻接点在顶点数组中的下标
struct ArcNode* next; // 指向下一个邻接点的指针
} ArcNode;
// 顶点表结点
typedef struct {
char data; // 顶点数据
ArcNode* first; // 指向第一个邻接点的指针
} VNode, AdjList[MAX_VERTEX_NUM];
// 图结构体
typedef struct {
AdjList vertices; // 顶点表
int vexnum, arcnum; // 顶点数、边数
} Graph;
// 初始化图
void initGraph(Graph* G) {
for (int i = 0; i < MAX_VERTEX_NUM; i++) {
G->vertices[i].data = '\0';
G->vertices[i].first = NULL;
}
G->vexnum = 0;
G->arcnum = 0;
}
// 添加边
void addArc(Graph* G, int v, int w) {
ArcNode* p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = w;
p->next = G->vertices[v].first;
G->vertices[v].first = p;
G->arcnum++;
}
// 深度优先遍历
void dfs(Graph G, int v, int* visited) {
visited[v] = 1;
printf("%c ", G.vertices[v].data);
ArcNode* p = G.vertices[v].first;
while (p != NULL) {
if (!visited[p->adjvex]) {
dfs(G, p->adjvex, visited);
}
p = p->next;
}
}
// 广度优先遍历
void bfs(Graph 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 w = queue[front++];
ArcNode* p = G.vertices[w].first;
while (p != NULL) {
if (!visited[p->adjvex]) {
printf("%c ", G.vertices[p->adjvex].data);
visited[p->adjvex] = 1;
queue[rear++] = p->adjvex;
}
p = p->next;
}
}
}
int main() {
Graph G;
initGraph(&G);
G.vertices[0].data = 'A';
G.vertices[1].data = 'B';
G.vertices[2].data = 'C';
G.vertices[3].data = 'D';
G.vertices[4].data = 'E';
addArc(&G, 0, 1);
addArc(&G, 0, 2);
addArc(&G, 1, 3);
addArc(&G, 1, 4);
addArc(&G, 2, 4);
int visited[MAX_VERTEX_NUM] = {0};
printf("深度优先遍历:");
dfs(G, 0, visited);
printf("\n");
for (int i = 0; i < MAX_VERTEX_NUM; i++) {
visited[i] = 0;
}
printf("广度优先遍历:");
bfs(G, 0, visited);
printf("\n");
return 0;
}
```
输出结果:
```
深度优先遍历:A B D E C
广度优先遍历:A B C D E
```
阅读全文