写一段代码一个无向图的BFS算法并用C语言实现
时间: 2023-05-14 17:06:05 浏览: 111
以下是一个用C语言实现的无向图BFS算法的代码段:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct node {
int vertex;
struct node* next;
} node;
typedef struct graph {
node* vertices[MAX_VERTICES];
int visited[MAX_VERTICES];
int num_vertices;
} graph;
void add_edge(graph* g, int src, int dest) {
node* new_node = (node*)malloc(sizeof(node));
new_node->vertex = dest;
new_node->next = g->vertices[src];
g->vertices[src] = new_node;
}
void bfs(graph* g, int start) {
int queue[MAX_VERTICES];
int front = 0, rear = 0;
queue[rear++] = start;
g->visited[start] = 1;
while (front < rear) {
int current = queue[front++];
printf("%d ", current);
node* temp = g->vertices[current];
while (temp) {
int adj_vertex = temp->vertex;
if (!g->visited[adj_vertex]) {
queue[rear++] = adj_vertex;
g->visited[adj_vertex] = 1;
}
temp = temp->next;
}
}
}
int main() {
graph* g = (graph*)malloc(sizeof(graph));
g->num_vertices = 6;
for (int i = 0; i < g->num_vertices; i++) {
g->vertices[i] = NULL;
g->visited[i] = 0;
}
add_edge(g, 0, 1);
add_edge(g, 0, 2);
add_edge(g, 1, 2);
add_edge(g, 2, 0);
add_edge(g, 2, 3);
add_edge(g, 3, 3);
printf("BFS traversal starting from vertex 2: ");
bfs(g, 2);
return 0;
}
```
这段代码实现了一个无向图的BFS算法,可以在main函数中添加更多的add_edge函数调用来构建不同的图,并在bfs函数中指定不同的起始顶点来进行遍历。
阅读全文