A strange lift(bfs)

Description

There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button "UP" , you will go up Ki floor,i.e,you will go to the i+Ki th floor,as the same, if you press the button "DOWN" , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can't go up high than N,and can't go down lower than 1. For example, there is a buliding with 5 floors, and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button "UP", and you'll go up to the 4 th floor,and if you press the button "DOWN", the lift can't do it, because it can't go down to the -2 th floor,as you know ,the -2 th floor isn't exist.
Here comes the problem: when you is on floor A,and you want to go to floor B,how many times at least he havt to press the button "UP" or "DOWN"?
 

Input

The input consists of several test cases.,Each test case contains two lines.
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,....kn.
A single 0 indicate the end of the input.
 

Output

For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can't reach floor B,printf "-1".
 

Sample Input

5 1 5
3 3 1 2 5
0
 

Sample Output

3
 
 
吴滔打击我了好久,终于写出来了,用了BFS,没用数组模拟,而是用了队列。
 
View Code
 1 #include<stdio.h>
2 #include<stdlib.h>
3 struct node
4 {
5 int first;
6 int step;
7 };
8 node q[300];
9 int N, A, B;
10 int num[300];
11 int BFS( int top, int a, int b )
12 {
13 int front, last;
14 front = last = 0;
15 int hash[300] = {0};
16 node g;
17 g.first = a;
18 g.step = 0;
19 q[last++] = g;
20 hash[a] = 1;
21 while( front < last )
22 {
23 g = q[front];
24 int x = g.first+num[g.first];
25 if( x <= top && !hash[x] )
26 {
27 q[last].first = x;
28 q[last].step = g.step+1;
29 hash[x] = 1;
30 if( x == b )
31 return g.step+1;
32 last++;
33 }
34 x = g.first-num[g.first];
35 if( x > 0 && !hash[x] )
36 {
37 q[last].first = x;
38 q[last].step = g.step+1;
39 hash[x] = 1;
40 if( x == b )
41 return g.step+1;
42 last++;
43 }
44 front++;
45 }
46 return -1;
47 }
48 int main()
49 {
50 while( scanf( "%d", &N ) && N )
51 {
52 scanf( "%d%d", &A, &B );
53 for( int i = 1; i <= N; i++ )
54 scanf( "%d", &num[i] );
55 if( A == B )
56 printf( "0\n" );
57 else
58 printf( "%d\n", BFS( N, A, B ) );
59 }
60 return 0;
61 }
原文地址:https://www.cnblogs.com/zsj576637357/p/2379463.html