bfs模板

这个。。。。我突然发现了这么回事,数据结构老师讲的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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值