C语言广度优先遍历代码
时间: 2023-12-20 18:31:26 浏览: 105
以下是C语言实现广度优先遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct Edgelink {
char Edge;
struct Edgelink *next;
} Edge, *Elink;
typedef struct Vertexlink {
char Vertex;
int visited;
Elink next;
} Vertex[MAX];
typedef struct Graph {
int Vnum;
Vertex List;
} Graph;
typedef struct Queue {
int front, rear;
int data[MAX];
} Queue;
void BFS_Link(Graph *G, int v) {
Queue Q;
int i, j;
Elink p;
Q.front = Q.rear = -1;
printf("%c ", G->List[v].Vertex);
G->List[v].visited = 1;
Q.data[++Q.rear] = v;
while (Q.front != Q.rear) {
i = Q.data[++Q.front];
p = G->List[i].next;
while (p != NULL) {
j = p->Edge - 'A' + 1;
if (G->List[j].visited == 0) {
printf("%c ", G->List[j].Vertex);
G->List[j].visited = 1;
Q.data[++Q.rear] = j;
}
p = p->next;
}
}
}
void BFS(Graph *G) {
int i;
for (i = 1; i <= G->Vnum; i++) {
G->List[i].visited = 0;
}
BFS_Link(G, 1);
}
int main() {
Graph G;
int i, j, k;
char c;
Elink p;
printf("请输入顶点数目:");
scanf("%d", &G.Vnum);
getchar();
printf("请输入顶点信息:");
for (i = 1; i <= G.Vnum; i++) {
scanf("%c", &G.List[i].Vertex);
G.List[i].visited = 0;
G.List[i].next = NULL;
getchar();
}
printf("请输入边信息(以#结束):\n");
while (1) {
scanf("%c", &c);
if (c == '#') {
break;
}
getchar();
scanf("%d%d", &i, &j);
getchar();
p = (Elink)malloc(sizeof(Edge));
p->Edge = G.List[j].Vertex;
p->next = G.List[i].next;
G.List[i].next = p;
p = (Elink)malloc(sizeof(Edge));
p->Edge = G.List[i].Vertex;
p->next = G.List[j].next;
G.List[j].next = p;
}
printf("广度优先遍历结果为:");
BFS(&G);
printf("\n");
return 0;
}
```
阅读全文