# 广度优先搜索算法—BFS

## 广度优先搜索算法—BFS

BFS算法：

void BFS(Graph graph, int begin) {
int value, i;
printf("%c ", graph[begin].data);
visited[begin] = 1;

CSeQueue *cs = NULL;
initSeQueue(&cs);
inSeQueue(cs, begin);

while(isEmpty(cs)) {
value = outSeQueue(cs);

for(i = firstVertex(graph, value); i >= 0; i = nextVertex(graph, value, i)) {
if(!visited[i]) {
printf("%c ", graph[i].data);
visited[i] = 1;
inSeQueue(cs, i);
}
}
}

destorySeQueue(&cs);
}
void BFSTravel(Graph graph, int begin) {
int i;

BFS(graph, begin);

for(i = 0; i < Num; i++) {
if(!visited[i]) {
BFS(graph, i);
}
}
}

#ifndef _CSEQUEUE_H_
#define _CSEQUEUE_H_

#include<stdio.h>
#include<malloc.h>

#define MAXSIZE 100
#define TRUE  1
#define FALSE 0

typedef int boolean;
typedef int dataType;
typedef struct CSeQueue {
dataType data[MAXSIZE];
int front, rear;
}CSeQueue;

void initSeQueue(CSeQueue **cs);
boolean inSeQueue(CSeQueue *cs, dataType data);
dataType outSeQueue(CSeQueue *cs);
void destorySeQueue(CSeQueue **cs);
boolean isEmpty(CSeQueue *cs);
boolean isFull(CSeQueue *cs);

boolean isFull(CSeQueue *cs) {
return (cs->rear + 1) % MAXSIZE == cs->front ? TRUE : FALSE;
}
boolean isEmpty(CSeQueue *cs) {
return cs->front == cs->rear ? TRUE : FALSE;
}
void destorySeQueue(CSeQueue **cs) {
if(*cs == NULL) {
return;
}

free(*cs);
}
dataType outSeQueue(CSeQueue *cs) {
if(cs->front == cs->rear) {
printf("队列为空.\n");
return FALSE;
}

cs->front = (cs->front + 1) % MAXSIZE;
return cs->data[cs->front];

}

boolean inSeQueue(CSeQueue *cs, dataType data) {
if((cs->rear + 1) % MAXSIZE == cs->front) {
printf("队列已满.\n");
return FALSE;
}
cs->rear = (cs->rear + 1) % MAXSIZE;
cs->data[cs->rear] = data;
}

void initSeQueue(CSeQueue **cs) {
if(*cs != NULL) {
printf("队列已经初始化过了.\n");
return;
}

(*cs) = (CSeQueue*)malloc(sizeof(CSeQueue));
(*cs)->front = (*cs)->rear = MAXSIZE-1;  //将 front, rear的值改为第一个单元的直接前驱的下标
}
#endif