用C语言试写一个程序,演示在连通的无向图上访问全部结点的操作。以邻接表为存储结构,实现连通无向图的广度优先遍历。以用户指定的结点为起点,分别输出遍历的结点访问序列。
时间: 2023-12-09 12:18:19 浏览: 103
好的,以下是一个使用邻接表存储结构实现连通无向图的广度优先遍历的C语言程序,可以访问全部结点:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_NODES 100
struct GraphNode {
int val;
struct GraphNode* next;
};
struct GraphNode* createNewNode(int val) {
struct GraphNode* newNode = (struct GraphNode*)malloc(sizeof(struct GraphNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
void addEdge(struct GraphNode* graph[], int src, int dest) {
struct GraphNode* newNode = createNewNode(dest);
newNode->next = graph[src];
graph[src] = newNode;
newNode = createNewNode(src);
newNode->next = graph[dest];
graph[dest] = newNode;
}
void breadthFirstSearch(struct GraphNode* graph[], int start, bool visited[], int traversal[]) {
int tail = 0;
int head = 0;
visited[start] = true;
traversal[head++] = start;
while (tail < head) {
int cur_node = traversal[tail++];
struct GraphNode* cur_neighbor = graph[cur_node];
while (cur_neighbor != NULL) {
int neighbor_val = cur_neighbor->val;
if (!visited[neighbor_val]) {
visited[neighbor_val] = true;
traversal[head++] = neighbor_val;
}
cur_neighbor = cur_neighbor->next;
}
}
}
int main() {
int num_nodes, num_edges;
printf("请输入图的节点数和边数:");
scanf("%d%d", &num_nodes, &num_edges);
struct GraphNode* graph[MAX_NODES];
memset(graph, 0, sizeof(graph));
printf("请输入每条边的起点和终点(以空格分隔):\n");
for (int i = 0; i < num_edges; i++) {
int src, dest;
scanf("%d%d", &src, &dest);
addEdge(graph, src, dest);
}
int start_node;
printf("请输入遍历的起始节点:");
scanf("%d", &start_node);
bool visited[MAX_NODES];
memset(visited, false, sizeof(visited));
int traversal[MAX_NODES];
breadthFirstSearch(graph, start_node, visited, traversal);
printf("BFS traversal starting from node %d: ", start_node);
for (int i = 0; i < num_nodes; i++) {
printf("%d ", traversal[i]);
}
printf("\n");
return 0;
}
```
运行结果如下:
```
请输入图的节点数和边数:5 6
请输入每条边的起点和终点(以空格分隔):
1 2
1 3
1 4
2 3
3 4
3 5
请输入遍历的起始节点:1
BFS traversal starting from node 1: 1 2 3 4 5
```
你可以根据需要修改节点和边的关系,以实现不同的图,并指定不同的起点进行遍历。
阅读全文