用C语言实现图的遍历算法
时间: 2023-10-29 21:06:13 浏览: 75
以下是使用邻接矩阵表示图的深度优先遍历和广度优先遍历的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 顶点数组
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num, edge_num; // 顶点数和边数
} Graph;
void create_graph(Graph *graph) {
printf("请输入顶点数和边数:");
scanf("%d%d", &graph->vertex_num, &graph->edge_num);
printf("请输入顶点:");
for (int i = 0; i < graph->vertex_num; i++) {
scanf("%d", &graph->vertex[i]);
}
for (int i = 0; i < graph->vertex_num; i++) {
for (int j = 0; j < graph->vertex_num; j++) {
graph->edge[i][j] = 0;
}
}
printf("请输入边(两个顶点编号,中间用空格隔开):\n");
for (int k = 0; k < graph->edge_num; k++) {
int i, j;
scanf("%d%d", &i, &j);
graph->edge[i][j] = 1; // 有向图
}
}
bool visited[MAX_VERTEX_NUM] = {false}; // 访问标记数组
void dfs(Graph *graph, int v) {
visited[v] = true;
printf("%d ", graph->vertex[v]);
for (int w = 0; w < graph->vertex_num; w++) {
if (graph->edge[v][w] == 1 && visited[w] == false) {
dfs(graph, w);
}
}
}
void bfs(Graph *graph, int v) {
bool visited[MAX_VERTEX_NUM] = {false}; // 访问标记数组
int queue[MAX_VERTEX_NUM] = {v}; // 队列
int front = 0, rear = 1; // 队头和队尾
visited[v] = true;
printf("%d ", graph->vertex[v]);
while (front < rear) {
int u = queue[front++];
for (int w = 0; w < graph->vertex_num; w++) {
if (graph->edge[u][w] == 1 && visited[w] == false) {
visited[w] = true;
printf("%d ", graph->vertex[w]);
queue[rear++] = w;
}
}
}
}
int main() {
Graph graph;
create_graph(&graph);
printf("深度优先遍历:");
for (int i = 0; i < graph.vertex_num; i++) {
if (visited[i] == false) {
dfs(&graph, i);
}
}
printf("\n广度优先遍历:");
bfs(&graph, 0);
printf("\n");
return 0;
}
```
其中,dfs函数是深度优先遍历的实现,bfs函数是广度优先遍历的实现,visited数组是访问标记数组,用于标记某个顶点是否已经访问过。
阅读全文