HDU 1548 bfs

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

int n,a,b;
int k[205];
bool vis[205];
struct node{
    int x,step;
};

int bfs(){
    memset(vis,false,sizeof(vis));
    queue<node> q;
    node cur,next;
    cur.x = a;
    vis[a] = 1;
    cur.step = 0;
    q.push(cur);
    while(!q.empty()){
        cur = q.front();
        q.pop();
        if(cur.x==b) return cur.step;
        for(int i=-1;i<=1;i+=2){
            next = cur;
            next.x += i*k[cur.x];
            if(!vis[next.x] && next.x>=1 && next.x<=n){
                vis[next.x] = 1;
                next.step++;
                q.push(next);
            }
        }
    }
    return -1;
}

int main(){
    while(1){
        scanf("%d",&n);
        if(n==0) break;
        scanf("%d%d",&a,&b);
        for(int i=1;i<=n;i++)
            scanf("%d",k+i);
        printf("%d\n",bfs());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42246923/article/details/80590879