HDU 1548 A strange lift (BFS)

BFS,每次有两个方向,分别把步数乘以1和-1就行了。要注意下起点终点重合的情况

#include<queue>
#include<iostream>
using namespace std;
int N,A,B;
int floor[220];
int visited[220];
typedef struct node
{
    int num;
    int steps;
}node;
queue<node>q;
int d[]={-1,1};
int bfs()
{
    while(!q.empty())q.pop();
    node s;
    s.num=A;
    s.steps=0;
    visited[A]=1;
    q.push(s);
    while(!q.empty())
    {
        node front = q.front();
        q.pop();
        if(front.num == B)return front.steps;
        for(int i=0;i<2;++i)
        {
            int t=front.num+floor[front.num]*d[i];
            if( t<=B&&t>=1 && visited[t]!=1)
            {
                node n;
                n.num=t;
                n.steps=front.steps+1;
                visited[t]=1;
                q.push(n);
            }
        }
    }
    return -1;
}
int main(int argc, char *argv[])
{
    //freopen("1548.in", "r", stdin);
    while(scanf("%d",&N)!=EOF)
    {
        if(N!=0)
        {
            scanf("%d %d",&A,&B);
            memset(floor,0,sizeof(visited));
            memset(visited,0,sizeof(visited));
            for(int i=1;i<=N;++i)
                scanf("%d",&floor[i]);
            int r=bfs();
            if(r>=0)
                printf("%d\n",r);
            else
                printf("-1\n");
        }
        else
            return 0;
    }
    return 0;
}


你可能感兴趣的:(HDU,bfs)