[洛谷]P1135 奇怪的电梯

!BFS不用回溯

题目描述

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 ii 层楼(1 \le i \le N1≤i≤N)上有一个数字 K_iKi​(0 \le K_i \le N0≤Ki​≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如: 3, 3, 1, 2, 53,3,1,2,5 代表了 K_iKi​(K_1=3K1​=3,K_2=3K2​=3,……),从 11 楼开始。在 11 楼,按“上”可以到 44 楼,按“下”是不起作用的,因为没有 -2−2 楼。那么,从 AA 楼到 BB 楼至少要按几次按钮呢?

输入格式

共二行。

第一行为三个用空格隔开的正整数,表示 N, A, BN,A,B(1 \le N \le 2001≤N≤200,1 \le A, B \le N1≤A,B≤N)。

第二行为 NN 个用空格隔开的非负整数,表示 K_iKi​。

输出格式

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

dfs:(80%过)本题数据,用bfs会更好通过

#include<iostream>
using namespace std;
int n, a, b;
int to[205], vis[205];
int ans = 1<<30;
void dfs(int now, int sum)
{
    vis[now] = 1;
    //结束
    if (now == b)
    {
        if (sum < ans)ans = sum;
    }
    //剪枝
    if (sum > ans)return;
    //
    if (now + to[now] <= n && !vis[now + to[now]]) dfs(now + to[now], sum + 1);
    if (now - to[now] >= 1 && !vis[now - to[now]])dfs(now - to[now], sum + 1);
}
int main()
{
    cin >> n >> a >> b;
    for (int i = 1; i <= n; i++)
        cin >> to[i];
    vis[a] = 1;
    dfs(a,0);
    if (ans == 1 << 30)cout<<"-1";
    else cout << ans;
    return 0;
}

bfs:(AC)

#include<iostream>
#include<queue>
using namespace std;
int n, a, b;
int to[210];
int vis[205];
struct node
{
    int x, step;
};
int bfs()
{
    vis[a] = 1;//第a楼为直接访问过的*****************************************
    node s1;
    s1.x = a, s1.step = 0;;
    queue<node>q;
    q.push(s1);
    while (!q.empty())
    {
        auto now = q.front();//取队首元素
        q.pop();//取完,首元素出队列
        if (now.x == b)//结束
        {
            return now.step;
        
        }
        //向上
        if (now.x + to[now.x] <= n&&!vis[now.x + to[now.x]])//判断是否合法并且未访问
        {
            vis[now.x + to[now.x]] = 1;//
            node tmp;
            tmp.x = now.x + to[now.x];
            tmp.step = now.step + 1;
            q.push(tmp);
        }
        //向下
        if (now.x - to[now.x] >=1&& !vis[now.x - to[now.x]])
        {
            vis[now.x - to[now.x]] = 1;
            node tmp1;
            tmp1.x = now.x - to[now.x];
            tmp1.step = now.step + 1;
            q.push(tmp1);
        }
    }
    return -1;//如果无正确答案,返回-1
}
int main()
{
    cin >> n >> a >> b;
    for (int i = 1; i <= n; i++)
        cin >> to[i];
    cout<<bfs();
    return 0;
}

over~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值