编程实现如下功能: (1)输入无向图的顶点数、边数及各条边的顶点对,建立用邻接表表示的无向图。 (2)对图进行深度优先搜索和广度优先搜索遍历,并分别输出其遍历序列。要求用c语言实现
时间: 2024-02-05 14:11:57 浏览: 75
以下是用 C 语言实现无向图的深度优先搜索和广度优先搜索遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表结构体
typedef struct node {
int vertex; // 顶点编号
struct node* next; // 指向下一个邻接点
} Node;
// 定义图结构体
typedef struct graph {
int num_vertices; // 顶点数
int num_edges; // 边数
Node** adj_list; // 邻接表数组
int* visited; // 记录顶点是否已被访问
} Graph;
// 创建邻接表节点
Node* create_node(int v) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->vertex = v;
new_node->next = NULL;
return new_node;
}
// 创建图
Graph* create_graph(int num_vertices, int num_edges) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->num_vertices = num_vertices;
graph->num_edges = num_edges;
graph->adj_list = (Node**)malloc(sizeof(Node*) * num_vertices);
graph->visited = (int*)malloc(sizeof(int) * num_vertices);
// 初始化邻接表和 visited 数组
for (int i = 0; i < num_vertices; i++) {
graph->adj_list[i] = NULL;
graph->visited[i] = 0;
}
// 构建邻接表
int u, v;
for (int i = 0; i < num_edges; i++) {
scanf("%d %d", &u, &v);
Node* new_node = create_node(v);
new_node->next = graph->adj_list[u];
graph->adj_list[u] = new_node;
new_node = create_node(u);
new_node->next = graph->adj_list[v];
graph->adj_list[v] = new_node;
}
return graph;
}
// 释放图所占空间
void free_graph(Graph* graph) {
for (int i = 0; i < graph->num_vertices; i++) {
Node* current = graph->adj_list[i];
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
free(graph->adj_list);
free(graph->visited);
free(graph);
}
// 深度优先搜索遍历
void dfs(Graph* graph, int vertex) {
graph->visited[vertex] = 1;
printf("%d ", vertex);
Node* current = graph->adj_list[vertex];
while (current != NULL) {
if (!graph->visited[current->vertex]) {
dfs(graph, current->vertex);
}
current = current->next;
}
}
// 广度优先搜索遍历
void bfs(Graph* graph, int vertex) {
int queue[graph->num_vertices];
int front = 0, rear = 0;
graph->visited[vertex] = 1;
printf("%d ", vertex);
queue[rear++] = vertex;
while (front < rear) {
int u = queue[front++];
Node* current = graph->adj_list[u];
while (current != NULL) {
if (!graph->visited[current->vertex]) {
graph->visited[current->vertex] = 1;
printf("%d ", current->vertex);
queue[rear++] = current->vertex;
}
current = current->next;
}
}
}
int main() {
int num_vertices, num_edges;
printf("请输入顶点数和边数:\n");
scanf("%d %d", &num_vertices, &num_edges);
Graph* graph = create_graph(num_vertices, num_edges);
printf("深度优先搜索遍历序列:");
for (int i = 0; i < num_vertices; i++) {
if (!graph->visited[i]) {
dfs(graph, i);
}
}
printf("\n");
for (int i = 0; i < num_vertices; i++) {
graph->visited[i] = 0;
}
printf("广度优先搜索遍历序列:");
for (int i = 0; i < num_vertices; i++) {
if (!graph->visited[i]) {
bfs(graph, i);
}
}
printf("\n");
free_graph(graph);
return 0;
}
```
输入格式为:
```
顶点数 边数
边的起点 边的终点
...
```
例如:
```
5 6
0 1
0 2
1 2
1 3
2 4
3 4
```
输出为:
```
深度优先搜索遍历序列:0 1 2 4 3
广度优先搜索遍历序列:0 1 2 3 4
```
阅读全文
相关推荐


















