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

题目链接:https://www.luogu.org/problemnew/show/P1135

题目描述

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 i 层楼 (1iN) 上有一个数字Ki(0KiN) 。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3,3,1,2,5 代表了Ki(K1=3,K2=3,) ,从 1 楼开始。在 1楼,按“上”可以到 4 楼,按“下”是不起作用的,因为没有 2 楼。那么,从 A 楼到 B 楼至少要按几次按钮呢?

输入格式:

共二行。

第一行为 3 个用空格隔开的正整数,表示N,A,B(1N200,1A,BN) 。

第二行为 N 个用空格隔开的非负整数,表示Ki 。

输出格式:

一行,即最少按键次数,若无法到达,则输出 1 。

输入样例#1: 
5 1 5
3 3 1 2 5
输出样例#1: 
3

裸的bfs
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int n, a, b;
struct node
{
    int x, step;
};
int arr[210];
int vis[210];
queue<node>q;

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];
            vis[next.x] = 1;
            next.step=now.step+1;
            q.push(next);
        }    
        if (now.x - arr[now.x] >= 1 && !vis[now.x - arr[now.x]])           //向下坐电梯
        {
            next.x = now.x - arr[now.x];
            vis[next.x] = 1;
            next.step = now.step + 1;
            q.push(next);
        }
    }
    return -1;
}

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

2018-05-31
原文地址:https://www.cnblogs.com/00isok/p/9119753.html