图的广度优先遍历借助 队列 实现。
#include"stdio.h"
#include"malloc.h"
#define SIZE 10
/*************队列************/
#define INITSIZE 10
#define INNCREASE 5
typedef int ElemType;
typedef struct{
ElemType *base;
ElemType *front;
ElemType *rear;
int length;
int size;
}Queue;
void init_queue(Queue *q){
q->front = q->base = (ElemType *)malloc(INITSIZE*sizeof(ElemType));
q->rear = q->front -1;
q->length = 0;
q->size = INITSIZE;
}
void push(Queue *q, ElemType e){
//这个判断条件
if(q->base + q->size <= q->rear){
//length >= size
q->front = (ElemType *)realloc(q->front, (INITSIZE+INNCREASE)*sizeof(ElemType));
q->rear = q->front + q->size - 1;
q->size += INNCREASE;
}
*++q->rear = e;
q->length++;
}
void pop(Queue *q, ElemType *e){
if(q->front == q->rear+1){
printf("THE QUEUE IS EMPTY\n");
return ;
}
*e = *q->front++;
q->length--;
}
int empty(Queue *q){
if(q->rear == q->front -1)
return 1;
return 0;
}
/*************图************/
typedef struct{
int e_num; //边数
int v_num; //顶点个数
int links[SIZE][SIZE]; //邻接矩阵
char vexs[SIZE];
}Graph;
void build(Graph *ph){
printf("输入顶点个数:");
scanf("%d",&ph->v_num);
printf("输入边数:");
scanf("%d",&ph->e_num);
printf("顶点序列:");
scanf("%s",&ph->vexs);
for(int i=1; i<=ph->v_num; i++){
for(int j=1; j<=ph->v_num; j++){
ph->links[i][j] = 0;
}
}
for(int j = 1; j<=ph->e_num; j++){
int start,end,value;
printf("第%d条边:",j);
scanf("%d %d %d",&start,&end,&value);
ph->links[start][end] = value;
ph->links[end][start] = value;
}
}
void show(Graph *ph){
printf("顶点序列:\n");
printf("%s",ph->vexs);
printf("\n");
printf("邻接矩阵:\n");
for(int i=1; i<=ph->v_num; i++){
for(int j=1; j<= ph->v_num; j++){
printf("%2d",ph->links[i][j]);
}
printf("\n");
}
printf("\n");
}
//一次广度优先遍历
void once_bfs(Graph *ph, Queue *q, int start, int visited[]){
init_queue(q);
visited[start] = 1; //标记已访问
printf("%2c",ph->vexs[start-1]);
push(q,start);
while(!empty(q)){
int nod;
pop(q,&nod);
for(int i=1; i<=ph->v_num; i++){
if(ph->links[nod][i] != 0 && visited[i] == 0){
visited[i] = 1;
printf("->");
printf("%2c",ph->vexs[i-1]);
push(q,i);
}
}
}
}
//一次就遍历结束的图,仅限于连通图
//对于非连通图,需要一次循环
void bfs(Graph *ph,Queue *q){
int visited[SIZE];
for(int i=0; i<=ph->v_num; i++){
visited[i] = 0;
}
for(int i=1; i<=ph->v_num; i++){
if(visited[i] == 0)
once_bfs(ph,q,i,visited);
}
}
int main(){
Graph graph;
Queue queue;
build(&graph);
show(&graph);
bfs(&graph,&queue);
return 0;
}