图的广度优先搜索(采用邻接表存储方式)
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; }
相关文章推荐
- 判断网络状态
- oracle查看和修改最大连接数
- attribute 的名字重复的问题
- laravel学习随记1
- Wishbone接口Altera JTAG UART
- POJ 3249 Test for Job【DAG图上的最短路问题】
- 【Leetcode】Count Primes
- Android之OnClick事件监听
- pixhawk 光流--位置估计--姿态估计--位置控制--姿态控制
- 【Leetcode】Kth Largest Element in an Array
- leetcode (31) Next Permutation
- Sublime Text3激活 破解
- 触发器
- Android activity任务栈和四中启动模式
- hdu 4183(网络流)
- 网页文字滚动的实现
- 【Leetcode】House Robber
- linux安全防护中迅速排查的一些命令
- 【Leetcode】Best Time to Buy and Sell Stock
- JSP 实用程序之简易图片验证码