标签:style class blog code ext 2014
继续校赛前的建图任务,当时只写了DFS遍历,今天把BFS也写了一下。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> const int maxe = 10001; using namespace std; struct node{ int to,w; node *next; }*head[maxe];//head[a]以a为起点的第一条边 int n,m; bool visbfs[maxe]={0}; bool visdfs[maxe]={0}; void init()//初始化 { memset(head,NULL,sizeof(head)); memset(visbfs,0,sizeof(visbfs)); memset(visdfs,0,sizeof(visdfs)); } void add(int a,int b,int c)//加边 { node *p = new node; p->to = b; p->w = c; p->next = head[a];//指向a的下一条边 head[a] = p; } void Print()//打印原图 { int i; for(i = 1;i<=n;i++) { node *q; for(q = head[i];q!=NULL;q=q->next) { printf("%d->%d %d\n",i,q->to,q->w); } } } void BFS(int x) { int q[maxe],jin = 0,chu = 0,st; visbfs[x] = true; q[jin++] = x; node *point; while(chu < jin) { st = q[chu++]; printf("%d\n",st); for(point = head[st];point!=NULL;point = point->next) { if(!visbfs[point->to]) { q[jin++] = point->to; visbfs[point->to] = true; } } } } int main() { int a,b,c,in; while(scanf("%d%d",&n,&m)) { init(); for(int i = 0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); add(a,b,c); add(b,a,c); } in = 1;//以1为例,开始遍历 puts("连接方式"); Print(); puts("bfs搜索"); BFS(in); } return 0; }
建图方式之“邻接链表” BFS搜索,布布扣,bubuko.com
标签:style class blog code ext 2014
原文地址:http://blog.csdn.net/wjw0130/article/details/31018337