BFS

HDU 1548
#include<bits/stdc++.h>
using namespace std;
int a[202];
int v[202];
int step[202];
int head,en;
int n,be,b;
int bfs()
{
    queue<int>q;
    q.push(be);//开始的楼层入队
    v[be]=1;
    step[be]=0;
    while(!q.empty())//
    {
        head=q.front();//当前楼层
        q.pop();
        for(int i=0; i<2; i++)
        {
            if(i==0)
                en=head+a[head];//UP
            else
                en=head-a[head];//Down
            if(en<1||en>n)
                continue;//出界
            if(!v[en])//不能回的走过的地方
            {
                q.push(en);
                v[en]=1;
                step[en]=step[head]+1;
            }
            if(en==b)
                return step[en];//成功到达
        }
    }
    return -1;



}
int main()//1548
{
    while(cin>>n&&n!=0)
    {
        memset(v,0,sizeof(v));
        memset(step,0,sizeof(step));
        scanf("%d %d",&be,&b);
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
        }
        printf("%d\n",bfs());
    }

}
HDU 1072
#include<bits/stdc++.h>
using namespace std;
int n,m;//行列
int a[20][20];//房间排列
int sum;
int b[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
struct node{
    int x,y;
    int step,ti;


};
node tmp;
void bfs()
{
    node t;
    queue<node>q;
    q.push(tmp);
    while(!q.empty()){
        tmp=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            t.x=tmp.x+b[i][0];
            t.y=tmp.y+b[i][1];
            t.step=tmp.step-1;
            t.ti=tmp.ti+1;
            if(t.x<=0||t.x>n||t.y<=0||t.y>m||t.step<=0)continue;
            if(a[t.x][t.y]==0)continue;
            if(a[t.x][t.y]==3)
            {
                sum=t.ti;
                return ;
            }
            else if(a[t.x][t.y]==1){
                q.push(t);//继续bfs
            }
            else if(a[t.x][t.y]==4)
            {
                t.step=6;
                a[t.x][t.y]=1;//不回头
                q.push(t);

            }
        }
    }


}
int main()
{
    int N;
    int bn,bm,en,em;//开始和结束的坐标
    cin>>N;
    for(int i=0;i<N;i++){
        scanf("%d %d",&n,&m);//行列
        for(int x=1;x<=n;x++){
            for(int y=1;y<=m;y++){
                scanf("%d",&a[x][y]);
                if(a[x][y]==2){
                    tmp.x=x;
                    tmp.y=y;
                    tmp.step=6;
                    tmp.ti=0;
                }

            }

        }//
       sum=-1;
        bfs();
     printf("%d\n",sum);




    }
    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值