编程实现如下功能: (1)输入无向图的顶点数、边数及各条边的顶点对,建立用邻接表表示的无向图。 (2)对图进行深度优先搜索和广度优先搜索遍历,并分别输出其遍历序列。 c语言
时间: 2024-02-05 14:13:37 浏览: 34
以下是C语言实现代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表节点结构体
typedef struct node {
int vertex; // 存储顶点
struct node* next; // 存储下一个节点
} Node;
// 定义邻接表结构体
typedef struct graph {
int num_vertices; // 存储顶点数
Node** adj_list; // 存储邻接表
int* visited; // 存储访问标记
} Graph;
// 创建节点
Node* create_node(int v) {
Node* node = (Node*)malloc(sizeof(Node));
node->vertex = v;
node->next = NULL;
return node;
}
// 添加边
void add_edge(Graph* G, int src, int dest) {
// 添加从src到dest的边
Node* node = create_node(dest);
node->next = G->adj_list[src];
G->adj_list[src] = node;
// 添加从dest到src的边
node = create_node(src);
node->next = G->adj_list[dest];
G->adj_list[dest] = node;
}
// 创建图
Graph* create_graph(int num_vertices, int num_edges) {
Graph* G = (Graph*)malloc(sizeof(Graph));
G->num_vertices = num_vertices;
G->adj_list = (Node**)malloc(num_vertices * sizeof(Node*));
G->visited = (int*)malloc(num_vertices * sizeof(int));
for (int i = 0; i < num_vertices; i++) {
G->adj_list[i] = NULL;
G->visited[i] = 0;
}
int src, dest;
for (int i = 0; i < num_edges; i++) {
scanf("%d %d", &src, &dest);
add_edge(G, src, dest);
}
return G;
}
// DFS遍历
void dfs(Graph* G, int vertex) {
G->visited[vertex] = 1;
printf("%d ", vertex);
Node* adj_list = G->adj_list[vertex];
while (adj_list != NULL) {
int adj_vertex = adj_list->vertex;
if (G->visited[adj_vertex] == 0) {
dfs(G, adj_vertex);
}
adj_list = adj_list->next;
}
}
// BFS遍历
void bfs(Graph* G, int start_vertex) {
int* queue = (int*)malloc(G->num_vertices * sizeof(int));
int front = -1, rear = -1;
G->visited[start_vertex] = 1;
queue[++rear] = start_vertex;
while (front != rear) {
int vertex = queue[++front];
printf("%d ", vertex);
Node* adj_list = G->adj_list[vertex];
while (adj_list != NULL) {
int adj_vertex = adj_list->vertex;
if (G->visited[adj_vertex] == 0) {
G->visited[adj_vertex] = 1;
queue[++rear] = adj_vertex;
}
adj_list = adj_list->next;
}
}
}
int main() {
int num_vertices, num_edges;
scanf("%d %d", &num_vertices, &num_edges);
Graph* G = create_graph(num_vertices, num_edges);
printf("DFS遍历序列:");
for (int i = 0; i < num_vertices; i++) {
if (G->visited[i] == 0) {
dfs(G, i);
}
}
printf("\nBFS遍历序列:");
for (int i = 0; i < num_vertices; i++) {
G->visited[i] = 0;
}
bfs(G, 0);
return 0;
}
```
该程序首先通过 `create_graph` 函数创建了一个无向图的邻接表,并通过 `add_edge` 函数添加边。然后,分别使用深度优先搜索和广度优先搜索遍历整张图,并输出遍历序列。
阅读全文