Hdu 1548 A strange lift(BFS)

Problem地址:http://acm.hdu.edu.cn/showproblem.php?pid=1548

 

一道简单的bfs,适合新手。你现在所在的电梯层为一个节点,而你从这个节点可以拜访另外两个节点(电梯向上走为一个节点,电梯向下走有一个节点),而拜访的时候自然也要避免拜访重复,否则会陷入死循环。

 

#include <iostream>
#include <queue>
using namespace std;

const int maxn = 200+10;
int N,A,B;
int K[maxn];
bool vis[maxn];
typedef struct node{
    int floor;
    int walk;
}node;

int bfs()
{
    memset(vis,false,sizeof(vis));
    queue <node> qf;
    node t, next;
    t.floor=A;
    t.walk=0;
    vis[ t.floor ]=true;
    qf.push(t);
    while( !qf.empty() )
    {
        t=qf.front();
        qf.pop();
        if(t.floor==B)
            return t.walk;
        next.walk=t.walk+1;
        next.floor=t.floor+K[t.floor];
        if( next.floor>=0 && next.floor<=N && !vis[next.floor])
            {
                qf.push(next);
                vis[ next.floor ]=true;
            }
        next.floor=t.floor-K[t.floor];
        if( next.floor>=0 && next.floor<=N && !vis[next.floor])
            {
                qf.push(next);
                vis[ next.floor ]=true;
            }
    }
    return -1;
}

int main()
{
    int i;
    while(cin>>N && N)
    {
        cin>>A>>B;
        for(i=1;i<=N;i++)
            cin>>K[i];
        cout<<bfs()<<endl;
    }
    return 0;
}

 

posted @ 2014-09-17 22:24  Emerald  阅读(165)  评论(0编辑  收藏  举报