奇怪的电梯(广度优先搜索)

本文介绍了一种基于广度优先搜索(BFS)的电梯路径寻优算法,旨在找到从A楼到B楼所需的最少按键次数。通过记录每一步的状态并回溯最佳路径,解决了特定条件下电梯移动的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Input

输入文件共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。

Output

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

Sample Input

 

5 1 5
3 3 1 2 5

 

Sample Output

 

3


解题思路:先读入数据,用广搜的思想,寻找从A楼道B楼的最佳路径,然后记录下来,最后输出的时候递归回去就行了。


程序:
const
  maxn=1000;

var
  father,state,a,f:array[1..maxn] of longint;
  n,a1,b,ans:longint;

procedure init;
  var
    i:longint;
  begin
    readln(n,a1,b);
    for i:=1 to n do
      read(a[i]);
    f[a1]:=1;
    ans:=0;
end;

function check(x:longint):boolean;
  begin
    if (x>0) and (x<=n) and (f[x]=0) then exit(true);
    check:=false;
end;

procedure dg(x:longint);
  begin
    if x=0 then exit;
    dg(father[x]);
    inc(ans);
end;

procedure bfs;
  var
    h,t:longint;
  begin
    h:=0;
    t:=1;
    state[1]:=a1;
    father[1]:=0;
    repeat
      inc(h);
      if check(state[h]+a[state[h]]) then
        begin
          inc(t);
          state[t]:=state[h]+a[state[h]];
          father[t]:=h;
          f[state[t]]:=1;
          if state[t]=b then
            begin
              dg(t);
              break;
            end;
        end;
      if check(state[h]-a[state[h]]) then
        begin
          inc(t);
          state[t]:=state[h]-a[state[h]];
          father[t]:=h;
          f[state[t]]:=1;
          if state[t]=b then
            begin
              dg(t);
              break;
            end;
        end;
    until h>=t;
    if h>=t then writeln(-1)
      else writeln(ans-1);
end;

begin
  init;
  if a1=b then writeln(0)
  else bfs;
end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值