C语言图的遍历BFS领接表
时间: 2024-03-16 17:37:46 浏览: 56
以下是C语言图的遍历BFS邻接表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 1000
typedef struct ArcNode {
int adjvex;
struct ArcNode *next;
} ArcNode;
typedef struct VNode {
int data;
ArcNode *first;
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
} ALGraph;
void BFS(ALGraph G, int v, int visited[]) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
visited[v] = 1;
printf("%d ", v);
queue[rear++] = v;
while (front != rear) {
int w = queue[front++];
for (ArcNode *p = G.vertices[w].first; p; p = p->next) {
int u = p->adjvex;
if (!visited[u]) {
visited[u] = 1;
printf("%d ", u);
queue[rear++] = u;
}
}
}
}
int main() {
int n, m, v;
scanf("%d%d%d", &n, &m, &v);
ALGraph G;
G.vexnum = n;
G.arcnum = m;
for (int i = 1; i <= n; i++) {
G.vertices[i].data = i;
G.vertices[i].first = NULL;
}
for (int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
ArcNode *p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = v;
p->next = G.vertices[u].first;
G.vertices[u].first = p;
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = u;
p->next = G.vertices[v].first;
G.vertices[v].first = p;
}
int visited[MAX_VERTEX_NUM] = {0};
BFS(G, v, visited);
return 0;
}
```
阅读全文