C语言利用邻接矩阵实现图的深度优先遍历和广度优先遍历
时间: 2024-06-13 14:07:20 浏览: 114
使用邻接矩阵实现图的深度优先遍历和广度优先遍历的C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 20
typedef char VertexType;
typedef int EdgeType;
typedef struct {
VertexType vertex[MAX_VERTEX_NUM];
EdgeType edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertex_num, edge_num;
} MGraph;
bool visited[MAX_VERTEX_NUM];
// 初始化邻接矩阵
void InitMGraph(MGraph *G) {
int i, j;
for (i = 0; i < G->vertex_num; i++) {
for (j = 0; j < G->vertex_num; j++) {
G->edge[i][j] = 0;
}
}
}
// 深度优先遍历
void DFS(MGraph *G, int v) {
int i;
visited[v] = true;
printf("%c ", G->vertex[v]);
for (i = 0; i < G->vertex_num; i++) {
if (G->edge[v][i] && !visited[i]) {
DFS(G, i);
}
}
}
// 广度优先遍历
void BFS(MGraph *G, int v) {
int i, queue[MAX_VERTEX_NUM], front = 0, rear = 0;
visited[v] = true;
printf("%c ", G->vertex[v]);
queue[rear++] = v;
while (front != rear) {
int w = queue[front++];
for (i = 0; i < G->vertex_num; i++) {
if (G->edge[w][i] && !visited[i]) {
visited[i] = true;
printf("%c ", G->vertex[i]);
queue[rear++] = i;
}
}
}
}
int main() {
MGraph G;
int i, j, v;
printf("请输入图的顶点数和边数:");
scanf("%d%d", &G.vertex_num, &G.edge_num);
printf("请输入图的顶点信息:");
for (i = 0; i < G.vertex_num; i++) {
scanf(" %c", &G.vertex[i]);
}
InitMGraph(&G);
printf("请输入图的边信息:\n");
for (i = 0; i < G.edge_num; i++) {
printf("请输入第%d条边的起点和终点:", i + 1);
scanf("%d%d", &v, &j);
G.edge[v][j] = G.edge[j][v] = 1;
}
printf("深度优先遍历结果:");
for (i = 0; i < G.vertex_num; i++) {
visited[i] = false;
}
for (i = 0; i < G.vertex_num; i++) {
if (!visited[i]) {
DFS(&G, i);
}
}
printf("\n广度优先遍历结果:");
for (i = 0; i < G.vertex_num; i++) {
visited[i] = false;
}
for (i = 0; i < G.vertex_num; i++) {
if (!visited[i]) {
BFS(&G, i);
}
}
return 0;
}
```
阅读全文