HDU 1548 A strange lift

简单的广搜

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

int map[205],step[205],a[205];
int n,start,end,res;

bool check(int x)
{
    if ((x>0)&&(x<=n)&&(map[x])) return true;
    else return false;
}

int bfs()
{
    int temp;
    if(start==end) return res;
    queue<int> Q;
    Q.push(start);
    step[start]=0;
    map[start]=false;
    while(!Q.empty())
    {
        temp=Q.front();
        Q.pop();
        if (temp+a[temp]==end) return step[temp]+1;
        if (temp-a[temp]==end) return step[temp]+1;
        if (check(temp+a[temp]))
        {
            int now=temp+a[temp];
            Q.push(now);
            step[now]=step[temp]+1;
            map[now]=false; 
        }
        if (check(temp-a[temp]))
        {
            int now=temp-a[temp];
            Q.push(now);
            step[now]=step[temp]+1;
            map[now]=false; 
        }
    }
    return -1;
}

int main()
{
    while(scanf("%d",&n),n!=0)
    {
        scanf("%d%d",&start,&end);
        for(int i=1;i<=n;i++)
        {scanf("%d",&a[i]);map[i]=true;}
        res=0; res=bfs();
        printf("%d
",res);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/forever97/p/3541265.html