使用c语言写一个代码假设无向连通图采用邻接表存储。设计一个算法输出图G的一颗深度优先生成树
时间: 2024-05-15 20:17:15 浏览: 154
好的,这是一个关于无向连通图的算法问题,我可以回答。以下是用C语言编写的代码,实现输出图G的一颗深度优先生成树:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct _node {
int vertex;
struct _node *next;
} node;
node *graph[MAX_VERTICES] = { NULL };
int visited[MAX_VERTICES] = { 0 };
void add_edge(int u, int v) {
node *new_node = (node*)malloc(sizeof(node));
new_node->vertex = v;
new_node->next = graph[u];
graph[u] = new_node;
}
void dfs(int v) {
visited[v] = 1;
printf("%d ", v);
node *adj_list = graph[v];
while (adj_list != NULL) {
int connected_vertex = adj_list->vertex;
if (!visited[connected_vertex]) {
dfs(connected_vertex);
}
adj_list = adj_list->next;
}
}
void dfs_spanning_tree(int v) {
visited[v] = 1;
node *adj_list = graph[v];
while (adj_list != NULL) {
int connected_vertex = adj_list->vertex;
if (!visited[connected_vertex]) {
printf("(%d,%d) ", v, connected_vertex);
dfs_spanning_tree(connected_vertex);
}
adj_list = adj_list->next;
}
}
int main() {
int vertices, edges, i, u, v;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
printf("Enter the number of edges: ");
scanf("%d", &edges);
for (i = 0; i < edges; i++) {
printf("Enter the edge (u, v): ");
scanf("%d%d", &u, &v);
add_edge(u, v);
add_edge(v, u);
}
printf("\nDepth First Traversal: ");
dfs(0);
printf("\n\nDepth First Spanning Tree: ");
dfs_spanning_tree(0);
return 0;
}
```
这段代码使用邻接表存储无向连通图,通过深度优先搜索算法实现输出一颗深度优先生成树。
阅读全文
相关推荐


















