P1135 奇怪的电梯

这是一道洛谷的黄题哈,这道题可以用广搜或者队列来写,我这边是使用广搜来写,主要思路:我要么往上要么往下所以用广搜则比较好写,bfs里面只需要判断是往上还是往下即可这边不多说放AC代码

#include <bits/stdc++.h>
using namespace std;
int n,a,b;
int c[205];
bool vis[205];
struct node{
    int x,step;
};
int bfs(int x){
    node now,pos,next;
    now.x = x,now.step=0;
    queue<node>q;
    q.push(now);
    while(!q.empty()){
        pos = q.front();
        q.pop();
        if(pos.x == b){
            return pos.step;
        }
        int f = -1;
        for(int i = 0;i < 2; i++){
            int bx = pos.x + c[pos.x]*f;
            f = f*-1;
            if(bx < 0 || bx > n) continue;
            if(vis[bx] == 1) continue;
            vis[bx]=1;
            next.x=bx;next.step=pos.step+1;
            q.push(next);
        }
    }
    return -1;
}
int main(){
    cin >> n >> a >> b;
    for(int i = 1; i <= n; i++){
        cin >> c[i];
    }
    vis[a]=1;
    cout << bfs(a);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值