这个。。。。我突然发现了这么回事,数据结构老师讲的bfs和我学的bfs是一个东西吗????。。。以前的是邻接矩阵的模板。。。现在存一个邻接表的吧。那个。校选终于结束了,我终于有时间写博客,写五子棋,写数据结构大作业了。
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int other[MaxN + 5] , last[MaxN + 5] , pre[MaxN + 5] , all = -1 ,ed ,a, b , x , y , dr,
m , n , dis[MaxN + 5 ] , vis[MaxN + 5] , seq[MaxN + 5];
void bfs(int s)
{
for(int i = 1 ; i <= n ; i++) dis[i] = 1 << 30;
int now , tail , head;
dis[s] = 0;
seq[head] = s , vis[s] = 1;
while(head <= tail){
now = seq[head];
ed = last[now];
while(ed != -1){
dr = last[now];
if(!vis[dr]){
vis[dr] = 1;
seq[++tail] = dr;
dis[dr] = dis[now] + 1;
}
ed = pre[ed];
}
head++;
}
}
void Build(int x , int y)
{
pre[++all] = last[x];
last[x] = all;
other[all] = y;
}
void Init()
{
memset(last , -1 , sizeof(last));
}
int main()
{
scanf("%d",&n);
Init();
for(int i = 1 ; i <= n ; i++){
scanf("%d %d",&a , &b);
Build(a , b);
Build(b , a);
}
bfs(1);
}