广度优先搜索遍历类似于树的按层次遍历的过程。操作步骤:
假设从图中某顶点v出发,在访问了v之后一次访问v的各个未曾访问过的邻接点,然后分别从这些邻接点出发一次访问他们的邻接点,并使“先被访问的顶点的邻接点”先于“后被访问的顶点的邻结点”被访问,直至图中所有已被访问的顶点的邻接点都被访问到。若此时图中尚有顶点未被访问,则另选图中一个未曾被访问的顶点作为起始点,,重复上述过程,直至所有顶点都被访问到为止。换句话话说,广度优先遍历图的过程是以v为起始点,由近至远,依次访问和v有路径想通且路径长度为1,2。。。的顶点。
具体代码实现如下:
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 100
#define INFINITY 65535
typedef char VertexType;
typedef int EdgeType;
enum GraphType {DG,UG,DN,UN};
int visit[MaxVertexNum];
typedef struct {
VertexType Vertices[MaxVertexNum];
EdgeType Edges[MaxVertexNum][MaxVertexNum];
int n, e;
enum GraphType GType;
}MGraph;
typedef struct node {
int data;
struct node *next;
}Qnode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
void InitQueue(LinkQueue *Q) {
Q->front = Q->rear = (QueuePtr)malloc(sizeof(Qnode));
if (! Q->front) {
exit(-1);
}
Q->front->next = NULL;
}
void EnQueue(LinkQueue *Q,int e) {
QueuePtr p;
p = (QueuePtr)malloc(sizeof(Qnode));
if (!p) {
exit(-1);
}
p->data = e;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
}
void DeQueue(LinkQueue *Q,int *e) {
QueuePtr p;
if (Q->front == Q->rear) {
return;
}
p = Q->front->next;
*e = p->data;
Q->front->next = p->next;
if(Q->rear == p) {
Q->rear = Q->front;
}
free(p);
}
void CreateMType(MGraph *G) {
int i, j, k, w;
G->GType = UN;
printf("请输入顶点和边的数目:");
scanf("%d %d",&(G->n),&(G->e));
getchar();
printf("请输入顶点字符:");
for(i = 0; i < G->n; ++i) {
scanf("%c",&(G->Vertices[i]));
}
/******初始化边(INFINITY表示无穷大,即没有边)******/
for(i = 0; i < G->n; i++) {
for(j = 0; j < G->n; j++) {
G->Edges[i][j] = INFINITY;
}
}
printf("\n请输入顶点之间的边与权值:");
for(k = 0; k < G->e; k++) {
scanf("%d,%d,%d",&i,&j,&w);
G->Edges[i][j] = w;
G->Edges[j][i] = w;
}
}
int IsEmpty(LinkQueue *G) {
if (G->rear == G->front) {
return 1;
}
else {
return 0;
}
}
void BFS(MGraph *G,int i) {
LinkQueue Q;
int j, e;
InitQueue(&Q);
printf("广度优先搜索遍历顺序:");
if (!visit[i]) {
visit[i] = 1;
printf("%c ",G->Vertices[i]);
EnQueue(&Q, i);
while (! IsEmpty(&Q)) {
DeQueue(&Q, &e);
for (j = 0; j < G->n; j++) {
if (G->Edges[e][j] != INFINITY && visit[j] != 1) {
visit[j] = 1;
printf("%c ",G->Vertices[j]);
EnQueue(&Q, j);
}
}
}
}
}
int main(void) {
MGraph G;
CreateMType(&G);
BFS(&G,2);
return 0;
}
运行结果: