奇怪的电梯 求pascal(广度搜索版)

来源:百度知道 编辑:UC知道 时间:2024/06/02 16:45:24
奇怪的电梯
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第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

program gallane_Lift;
var n,i,j,l,a,b,p:longint;
lift,step:array[0..200] of longint;
begin
assign(input,'lift.in');
reset(input);
assign(output,'lift.out');
rewrite(output);
read(n,a,b);
for i:=1 to n do read(lift[i]);
for i:=1 to n do step[i]:=-1;
step[a]:=0;
p:=0; l:=1;
while (l>0) and (step[b]=-1) do
begin
l:=0;
for i:=1 to n do
if step[i]=p then
begin
j:=i-lift[i];
if (j>0) and (step[j]=-1) then
begin
step[j]:=p+1;
l:=l+1;
end;
j:=i+lift[i];
if (j<=n) and (step[j]=-1) then
begin
step[j]:=p+1;
l:=l+1;
end;
end;
p:=p+1;
end;
write(step[b]);
en