针对给定的无向图,实现图的深度优先遍历和广度优先遍历,并输出相应遍历结果用C语言
时间: 2023-11-22 11:53:13 浏览: 93
以下是使用C语言实现图的深度优先遍历和广度优先遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100 // 最大顶点数
// 定义图结构体
typedef struct {
int num_vertices; // 顶点数量
int adjacency_matrix[MAX_VERTICES][MAX_VERTICES]; // 邻接矩阵
} Graph;
// 定义队列结构体
typedef struct {
int front, rear;
int data[MAX_VERTICES];
} Queue;
// 初始化队列
void init_queue(Queue* queue) {
queue->front = -1;
queue->rear = -1;
}
// 判断队列是否为空
int is_queue_empty(Queue* queue) {
return queue->front == -1;
}
// 将数据入队
void enqueue(Queue* queue, int value) {
if (queue->front == -1) {
queue->front = 0;
}
queue->rear++;
queue->data[queue->rear] = value;
}
// 将数据出队
int dequeue(Queue* queue) {
int value = queue->data[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return value;
}
// 深度优先遍历
void dfs(Graph* graph, int visited[], int vertex) {
visited[vertex] = 1;
printf("%d ", vertex);
for (int i = 0; i < graph->num_vertices; i++) {
if (graph->adjacency_matrix[vertex][i] && !visited[i]) {
dfs(graph, visited, i);
}
}
}
// 广度优先遍历
void bfs(Graph* graph, int visited[], int vertex) {
Queue queue;
init_queue(&queue);
visited[vertex] = 1;
printf("%d ", vertex);
enqueue(&queue, vertex);
while (!is_queue_empty(&queue)) {
int current_vertex = dequeue(&queue);
for (int i = 0; i < graph->num_vertices; i++) {
if (graph->adjacency_matrix[current_vertex][i] && !visited[i]) {
visited[i] = 1;
printf("%d ", i);
enqueue(&queue, i);
}
}
}
}
int main() {
Graph graph;
graph.num_vertices = 5;
// 初始化邻接矩阵
for (int i = 0; i < graph.num_vertices; i++) {
for (int j = 0; j < graph.num_vertices; j++) {
graph.adjacency_matrix[i][j] = 0;
}
}
// 添加边
graph.adjacency_matrix[0][1] = 1;
graph.adjacency_matrix[0][2] = 1;
graph.adjacency_matrix[1][0] = 1;
graph.adjacency_matrix[1][2] = 1;
graph.adjacency_matrix[1][3] = 1;
graph.adjacency_matrix[2][0] = 1;
graph.adjacency_matrix[2][1] = 1;
graph.adjacency_matrix[2][3] = 1;
graph.adjacency_matrix[2][4] = 1;
graph.adjacency_matrix[3][1] = 1;
graph.adjacency_matrix[3][2] = 1;
graph.adjacency_matrix[3][4] = 1;
graph.adjacency_matrix[4][2] = 1;
graph.adjacency_matrix[4][3] = 1;
int visited[MAX_VERTICES] = {0};
printf("深度优先遍历:");
dfs(&graph, visited, 0);
printf("\n");
for (int i = 0; i < graph.num_vertices; i++) {
visited[i] = 0;
}
printf("广度优先遍历:");
bfs(&graph, visited, 0);
printf("\n");
return 0;
}
```
上述代码实现了一个无向图的深度优先遍历和广度优先遍历。其中,邻接矩阵储存了图的顶点之间的连通情况,使用递归实现了深度优先遍历,使用队列实现了广度优先遍历。在示例代码中,我们构建了一个包含5个顶点的图,并输出了深度优先遍历和广度优先遍历的结果。
阅读全文