有向图的邻接表存储,逐个链表输出,然后从0号顶点出发对该图进行广度优先搜索用C语言写
时间: 2024-02-06 14:11:17 浏览: 79
好的,以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表中的节点结构体
typedef struct AdjListNode {
int dest;
struct AdjListNode *next;
} AdjListNode;
// 定义邻接表结构体
typedef struct AdjList {
AdjListNode *head;
} AdjList;
// 定义图结构体
typedef struct Graph {
int V; // 顶点数目
AdjList *array;
} Graph;
// 添加边,src为起点,dest为终点
void addEdge(Graph *graph, int src, int dest) {
AdjListNode *newNode = (AdjListNode*)malloc(sizeof(AdjListNode));
newNode->dest = dest;
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}
// 初始化图
Graph *createGraph(int V) {
Graph *graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->array = (AdjList*)malloc(sizeof(AdjList) * V);
for (int i = 0; i < V; i++) {
graph->array[i].head = NULL;
}
return graph;
}
// 从顶点s开始进行BFS
void BFS(Graph *graph, int s) {
// 初始化visited数组,用于记录每个顶点是否被访问过
int *visited = (int*)malloc(sizeof(int) * graph->V);
for (int i = 0; i < graph->V; i++) {
visited[i] = 0;
}
// 创建队列,用于存储需要遍历的顶点
int *queue = (int*)malloc(sizeof(int) * graph->V);
int front = 0, rear = 0;
queue[rear++] = s;
// 标记起点已访问
visited[s] = 1;
// 遍历队列中的元素,直到队列为空
while (front < rear) {
// 取出队列头部元素
int cur = queue[front++];
// 输出当前访问的顶点
printf("%d ", cur);
// 遍历当前顶点的邻接表中的所有节点
AdjListNode *node = graph->array[cur].head;
while (node != NULL) {
// 如果当前节点未被访问,则将其加入队列中
if (visited[node->dest] == 0) {
queue[rear++] = node->dest;
visited[node->dest] = 1;
}
node = node->next;
}
}
free(visited);
free(queue);
}
int main() {
// 创建有向图
Graph *graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
addEdge(graph, 4, 5);
// 从0号顶点开始进行BFS
printf("BFS traversal starting from vertex 0: ");
BFS(graph, 0);
// 释放内存
for (int i = 0; i < graph->V; i++) {
AdjListNode *node = graph->array[i].head;
while (node != NULL) {
AdjListNode *tmp = node;
node = node->next;
free(tmp);
}
}
free(graph->array);
free(graph);
return 0;
}
```
输出结果为:
```
BFS traversal starting from vertex 0: 0 1 2 3 4 5
```
阅读全文