使用c语言写一个代码假设无向连通图采用邻接表存储。设计一个算法输出图G的一颗深度优先生成树
时间: 2024-05-06 15:21:27 浏览: 105
好的,对于您的问题,我可以提供以下 C 语言代码来实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表结点
typedef struct node {
int vertex;
struct node* next;
} Node;
// 定义邻接表
typedef struct adj_list {
Node* head;
} AdjList;
// 定义图结构
typedef struct graph {
int vertices;
AdjList* array;
} Graph;
// 初始化邻接表
Node* create_node(int vertex) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;
}
// 创建图
Graph* create_graph(int vertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->vertices = vertices;
graph->array = (AdjList*)malloc(vertices * sizeof(AdjList));
int i;
for (i = 0; i < vertices; ++i) {
graph->array[i].head = NULL;
}
return graph;
}
// 添加边
void add_edge(Graph* graph, int src, int dest) {
// 添加边(src -> dest)
Node* newNode = create_node(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// 添加边(dest -> src),由于无向图的存在,需要添加两条边
newNode = create_node(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
// 深度优先搜索
void dfs(int vertex, int* visited, Graph* graph) {
visited[vertex] = 1;
printf("%d ", vertex);
// 遍历顶点的每个邻接顶点
Node* adj_vertex = graph->array[vertex].head;
while (adj_vertex != NULL) {
if (!visited[adj_vertex->vertex]) {
dfs(adj_vertex->vertex, visited, graph);
}
adj_vertex = adj_vertex->next;
}
}
// 输出图 G 的一颗深度优先生成树
void dfs_spanning_tree(Graph* graph) {
int* visited = (int*)malloc(graph->vertices * sizeof(int));
int i;
for (i = 0; i < graph->vertices; ++i) {
visited[i] = 0;
}
// 从第一个顶点开始遍历
dfs(0, visited, graph);
}
// 主函数
int main() {
int vertices = 5;
Graph* graph = create_graph(vertices);
add_edge(graph, 0, 1);
add_edge(graph, 0, 2);
add_edge(graph, 1, 2);
add_edge(graph, 1, 3);
add_edge(graph, 2, 3);
add_edge(graph, 3, 4);
dfs_spanning_tree(graph);
return 0;
}
```
希望这可以帮助您解决问题!
阅读全文