简单BFS。。
#include"stdio.h" #include"string.h" #include"queue" using namespace std; struct node { int x,step; }q,p; int main() { int d[201],mark[202]; int a,b,n,i,ans; while(scanf("%d%d%d",&n,&a,&b)!=EOF) { ans=-1; if(n==0)break; for(i=1;i<=n;i++) scanf("%d",&d[i]); memset(mark,0,sizeof(mark)); p.x=a; p.step=0; queue<node>Q; Q.push(p); mark[a]=1; while(!Q.empty()) { p=Q.front(); Q.pop(); if(p.x==b) { ans=p.step;break; } q.step=p.step+1; q.x=p.x+d[p.x]; if(q.x>0&&q.x<=n&&mark[q.x]==0) { mark[q.x]=1; if(q.x==b) { ans=q.step;break; } Q.push(q); } q.x=p.x-d[p.x]; if(q.x>0&&q.x<=n&&mark[q.x]==0) { mark[q.x]=1; if(q.x==b) { ans=q.step;break; } Q.push(q); } } printf("%d\n",ans); } return 0; }