用c语言表示bfs的基本框架
时间: 2023-04-11 10:00:58 浏览: 96
BFS的基本框架可以用C语言表示如下:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 //定义队列的最大长度
int visited[MAX_SIZE]; //标记数组,用于记录节点是否被访问过
typedef struct {
int data[MAX_SIZE]; //队列数组
int front, rear; //队头和队尾指针
} Queue;
void initQueue(Queue *q) { //初始化队列
q->front = q->rear = 0;
}
int isEmpty(Queue *q) { //判断队列是否为空
return q->front == q->rear;
}
void enqueue(Queue *q, int x) { //入队操作
if (q->rear == MAX_SIZE) {
printf("Queue is full.\n");
exit(1);
}
q->data[q->rear++] = x;
}
int dequeue(Queue *q) { //出队操作
if (isEmpty(q)) {
printf("Queue is empty.\n");
exit(1);
}
return q->data[q->front++];
}
void bfs(int graph[][MAX_SIZE], int n, int start) { //BFS遍历
Queue q;
initQueue(&q);
visited[start] = 1;
enqueue(&q, start);
while (!isEmpty(&q)) {
int v = dequeue(&q);
printf("%d ", v);
for (int i = 0; i < n; i++) {
if (graph[v][i] && !visited[i]) {
visited[i] = 1;
enqueue(&q, i);
}
}
}
}
int main() {
int n, start;
printf("Enter the number of nodes: ");
scanf("%d", &n);
int graph[MAX_SIZE][MAX_SIZE];
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting node: ");
scanf("%d", &start);
printf("BFS traversal: ");
bfs(graph, n, start);
printf("\n");
return 0;
}
```
阅读全文