c语言实现图的深度优先遍历和广度优先遍历的代码
时间: 2023-12-05 18:39:42 浏览: 83
图的深度优先搜索遍历c代码实现
4星 · 用户满意度95%
以下是C语言实现图的深度优先遍历和广度优先遍历的代码:
深度优先遍历:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex;
struct ArcNode *nextarc;
} ArcNode;
typedef struct VNode {
char data;
ArcNode *firstarc;
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
} ALGraph;
int visited[MAX_VERTEX_NUM];
void CreateGraph(ALGraph *G) {
int i, j, k;
ArcNode *p;
printf("请输入顶点数和边数:\n");
scanf("%d%d", &G->vexnum, &G->arcnum);
printf("请输入顶点信息:\n");
for (i = 0; i < G->vexnum; i++) {
scanf(" %c", &G->vertices[i].data);
G->vertices[i].firstarc = NULL;
}
printf("请输入边的信息:\n");
for (k = 0; k < G->arcnum; k++) {
printf("请输入第%d条边的顶点序号:\n", k + 1);
scanf("%d%d", &i, &j);
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = j;
p->nextarc = G->vertices[i].firstarc;
G->vertices[i].firstarc = p;
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = i;
p->nextarc = G->vertices[j].firstarc;
G->vertices[j].firstarc = p;
}
}
void DFS(ALGraph *G, int v) {
ArcNode *p;
visited[v] = 1;
printf("%c ", G->vertices[v].data);
p = G->vertices[v].firstarc;
while (p != NULL) {
if (!visited[p->adjvex]) {
DFS(G, p->adjvex);
}
p = p->nextarc;
}
}
void DFSTraverse(ALGraph *G) {
int v;
for (v = 0; v < G->vexnum; v++) {
visited[v] = 0;
}
for (v = 0; v < G->vexnum; v++) {
if (!visited[v]) {
DFS(G, v);
}
}
}
void BFS(ALGraph *G, int v) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0, w;
ArcNode *p;
printf("%c ", G->vertices[v].data);
visited[v] = 1;
queue[rear++] = v;
while (front != rear) {
v = queue[front++];
p = G->vertices[v].firstarc;
while (p != NULL) {
w = p->adjvex;
if (!visited[w]) {
printf("%c ", G->vertices[w].data);
visited[w] = 1;
queue[rear++] = w;
}
p = p->nextarc;
}
}
}
void BFSTraverse(ALGraph *G) {
int v;
for (v = 0; v < G->vexnum; v++) {
visited[v] = 0;
}
for (v = 0; v < G->vexnum; v++) {
if (!visited[v]) {
BFS(G, v);
}
}
}
int main() {
ALGraph G;
CreateGraph(&G);
printf("深度优先遍历结果:");
DFSTraverse(&G);
printf("\n广度优先遍历结果:");
BFSTraverse(&G);
return 0;
}
```
阅读全文