洛谷 P1135 奇怪的电梯 【基础BFS】

《题目链接》


 

 

#include <bits/stdc++.h>
using namespace std;
#define REP(i,s,t) for(int i=s;i<=t;i++)
const int N = 205;
struct Node { int x, step; };
queue<Node>q;
int arr[N], vis[N];
int n, a, b;

int bfs() {
    Node now, next;
    while(!q.empty()) {
        now = q.front(); q.pop();
        if(now.x == b) { return now.step; }
        if(now.x + arr[now.x] <= 200 && !vis[now.x + arr[now.x]]) {        //向上坐电梯
            next.x = now.x + arr[now.x], next.step = now.step + 1;
            vis[next.x] = 1;
            q.push(next);
        }
        if(now.x - arr[now.x] >= 1 && !vis[now.x - arr[now.x]]) {          //向下坐电梯 
            next.x = now.x - arr[now.x], next.step = now.step + 1;
            vis[next.x] = 1;
            q.push(next);
        }
    }
    return -1;
}

int main() {
    cin >> n >> a >> b;
    memset(vis, 0, sizeof(vis));
    REP(i,1,n) scanf("%d", &arr[i]);
    Node now; now.x = a, now.step = 0;
    q.push(now);
    cout << bfs() <<endl;
    return 0;
}

 

 


2018-05-31
posted @ 2018-06-01 00:00  悠悠呦~  阅读(446)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end