用C语言实现图的深度优先遍历和广度优先遍历
时间: 2023-10-04 14:07:39 浏览: 86
图的深度优先遍历和广度优先遍历可以用C语言进行实现,下面是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
//图的邻接矩阵存储结构
typedef struct {
int vertex[MAX_VERTEX_NUM];
int arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertex_num, arc_num;
} Graph;
//创建图
void createGraph(Graph* G) {
printf("请输入图的顶点数和边数:");
scanf("%d%d", &G->vertex_num, &G->arc_num);
printf("请输入图的顶点:");
for (int i = 0; i < G->vertex_num; i++) {
scanf("%d", &G->vertex[i]);
}
for (int i = 0; i < G->vertex_num; i++) {
for (int j = 0; j < G->vertex_num; j++) {
G->arc[i][j] = 0;
}
}
printf("请输入图的边:\n");
for (int k = 0; k < G->arc_num; k++) {
int i, j;
scanf("%d%d", &i, &j);
G->arc[i][j] = 1;
G->arc[j][i] = 1;
}
}
//深度优先遍历
void DFS(Graph* G, int v, int* visited) {
visited[v] = 1;
printf("%d ", G->vertex[v]);
for (int i = 0; i < G->vertex_num; i++) {
if (G->arc[v][i] == 1 && visited[i] == 0) {
DFS(G, i, visited);
}
}
}
//广度优先遍历
void BFS(Graph* G, int v, int* visited) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
visited[v] = 1;
queue[rear++] = v;
printf("%d ", G->vertex[v]);
while (front < rear) {
int w = queue[front++];
for (int i = 0; i < G->vertex_num; i++) {
if (G->arc[w][i] == 1 && visited[i] == 0) {
visited[i] = 1;
queue[rear++] = i;
printf("%d ", G->vertex[i]);
}
}
}
}
int main() {
Graph G;
createGraph(&G);
int visited[MAX_VERTEX_NUM] = {0};
printf("深度优先遍历:");
for (int i = 0; i < G.vertex_num; i++) {
if (visited[i] == 0) {
DFS(&G, i, visited);
}
}
printf("\n广度优先遍历:");
for (int i = 0; i < G.vertex_num; i++) {
visited[i] = 0;
}
for (int i = 0; i < G.vertex_num; i++) {
if (visited[i] == 0) {
BFS(&G, i, visited);
}
}
return 0;
}
```
运行程序,输入图的顶点数和边数,以及图的顶点和边,即可得到图的深度优先遍历和广度优先遍历的结果。
阅读全文