用C语言完成基于邻接表表示法实现图的广度优先遍历
时间: 2023-12-18 20:02:28 浏览: 82
以下是使用邻接表表示法实现图的广度优先遍历的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 1000
#define QUEUE_SIZE 1000
typedef struct node {
int vertex;
struct node* next;
} node_t;
node_t* graph[MAX_NODES];
int visited[MAX_NODES];
int queue[QUEUE_SIZE];
int front = -1, rear = -1;
void add_edge(int src, int dest) {
node_t* new_node = malloc(sizeof(node_t));
new_node->vertex = dest;
new_node->next = graph[src];
graph[src] = new_node;
}
void bfs(int start) {
int i, vertex;
node_t* temp;
visited[start] = 1;
queue[++rear] = start;
while (front != rear) {
vertex = queue[++front];
printf("%d ", vertex);
for (temp = graph[vertex]; temp != NULL; temp = temp->next) {
i = temp->vertex;
if (!visited[i]) {
visited[i] = 1;
queue[++rear] = i;
}
}
}
}
int main() {
int n, e, i, src, dest;
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("Enter the number of edges: ");
scanf("%d", &e);
for (i = 0; i < n; i++) {
graph[i] = NULL;
visited[i] = 0;
}
printf("Enter the edges:\n");
for (i = 0; i < e; i++) {
scanf("%d %d", &src, &dest);
add_edge(src, dest);
add_edge(dest, src); // 如果是无向图,还要加上 dest 到 src 的边
}
printf("Enter the starting node: ");
scanf("%d", &src);
printf("BFS traversal starting from node %d: ", src);
bfs(src);
return 0;
}
```
这个程序使用了一个邻接表来表示图,输入时需要手动输入。第一行输入节点数和边数,接下来输入每条边连接的两个节点。最后输入起始节点,程序会输出从这个节点开始的广度优先遍历结果。
阅读全文