您的位置:首页 > 其它

图的广度优先搜索(采用邻接表存储方式)

2016-06-01 20:10 357 查看
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20

int visited[MAXSIZE];

typedef struct node{
int adjvex;
struct node * next;
}Node;

typedef struct{
int vertex;
Node * first;
}VNode;

typedef struct qnode{
int data;
struct qnode * next;
}Qnode;

typedef struct{
Qnode * front;
Qnode * rear;
}LinkQueue;

LinkQueue * init(){             //初始化队列
LinkQueue * lq;
Qnode * qn;
qn = (Qnode *)malloc(sizeof(Qnode));
lq = (LinkQueue *)malloc(sizeof(LinkQueue));

qn->next = NULL;
lq->front = qn;
lq->rear = qn;
return lq;
}

void inLinkQueue(LinkQueue * lq,int x){           //入队
Qnode * p = (Qnode *)malloc(sizeof(Qnode));
p->data = x;
p->next = NULL;
lq->rear->next = p;
lq->rear = p;
}

int outLinkQueue(LinkQueue * lq){           //出队
Qnode * p;
int x;
if(lq->front == lq->rear){
printf("队列为空\n");
return -1;
}else{
p = lq->front->next;
x = p->data;
lq->front->next = p->next;
free(p);
if(lq->front->next == NULL){
lq->rear = lq->front;
}
return x;
}
}

void create(VNode g[],int n,int e){         //创建无向图的邻接表
Node * p;
int i,j;

for(int t=0;t<n;t++){
g[t].vertex = t;
g[t].first = NULL;
}

for(int k=0;k<e;k++){
printf("请输入连通边i->j\n");
scanf("%d,%d",&i,&j);
p = (Node *)malloc(sizeof(Node));
p->adjvex = j;
p->next = g[i].first;
g[i].first = p;
p = (Node *)malloc(sizeof(Node));
p->adjvex = i;
p->next = g[j].first;
g[j].first = p;
}
}

void BFS(VNode g[]){                        //广度优先搜索
LinkQueue * lq = init();
Node * p;
int j;
printf("%4d",g[0].vertex);
visited[0] = 1;
inLinkQueue(lq,0);
while(lq->front != lq->rear){
j = outLinkQueue(lq);
p = g[j].first;
while(p != NULL){
if(!visited[p->adjvex]){
printf("%4d",g[p->adjvex].vertex);
inLinkQueue(lq,p->adjvex);
visited[p->adjvex] = 1;
}else{
p = p->next;
}
}
}
}

int main(){
VNode g[MAXSIZE];
int n,e;
printf("请输入节点的个数!\n");
scanf("%d",&n);
printf("请输入边的个数\n");
scanf("%d",&e);
create(g,n,e);
printf("广度优先搜索结果:\n");
BFS(g);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: