BFS——A strange lift

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#define M 200000010
#define INF 0x3f3f3f3f
using namespace std;

struct node{
    int floor,cnt;
};
int N,A,B;
int k[205];
bool vis[205];
int main()
{
    while(scanf("%d",&N)&& N){
        scanf("%d %d ",&A,&B);
        for(int i=1; i<=N; i++)
            scanf("%d",&k[i]);
        
        memset(vis,0,sizeof(vis));
        queue<node>q;
        while(!q.empty()) q.pop();
        
        node now,nex;
        now.floor = A; now.cnt = 0;
        vis[A] = 1;
        q.push(now);
        bool flag = 0;
        
        
        while(!q.empty()){
            now = q.front();         //取出一个元素
            q.pop();
            if(now.floor==B){       //如果到达目标地
                printf("%d\n",now.cnt);
                flag = 1;
                break;
            }
            //up
            int t = now.floor + k[now.floor];
            if(t>=1 && t<=N && !vis[t]){
                vis[t] = 1;
                nex.floor = t;
                nex.cnt = now.cnt+1;
                q.push(nex);
            }
            //down
            t = now.floor - k[now.floor];
            if(t>=1 && t<=N && !vis[t]){
                vis[t] = 1;
                nex.floor = t;
                nex.cnt = now.cnt+1;
                q.push(nex);
            }
        }
        if(!flag) printf("-1\n");
    }
    
    return 0;
}
发布了30 篇原创文章 · 获赞 0 · 访问量 682

猜你喜欢

转载自blog.csdn.net/jhckii/article/details/104128913
今日推荐