5 1 5 3 3 1 2 5 0Sample Output
3
分析:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int MAX = 11000;
struct Node
{
int to,step;
} node,nextnode;
int v[MAX],f[MAX];
int main()
{
int cas,n,m,i;
while(scanf("%d",&cas)&&cas)
{
scanf("%d%d",&m,&n);
memset(v,0,sizeof(v));
for(i=1; i<=cas; i++)
scanf("%d",&f[i]);//输入每层可以上下的层数
queuequ;//定义队列
while(!qu.empty())
{
qu.pop();
}
int t1,t2,flag=0;
node.step=0;//起始点
node.to=m;
qu.push(node);
v[node.to]=1;
while(!qu.empty())
{
node = qu.front();//取出首元素
qu.pop();
if(node.to == n)//如果到达终点
{
printf("%d\n",node.step);
flag=1;
break;
}
t1=node.to+f[node.to];//向上走
if(t1<=cas&&!v[t1])
{
v[t1]=1;
nextnode.to=t1;
nextnode.step=node.step+1;
qu.push(nextnode);
}
t1=node.to-f[node.to];//向下走
if(t1>=1&&!v[t1])
{
v[t1]=1;
nextnode.to=t1;
nextnode.step=node.step+1;
qu.push(nextnode);
}
}
if(!flag)//如果走不到
printf("-1\n");
}
return 0;
}