http://acm.hdu.edu.cn/showproblem.php?pid=1548
简单的BFS
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a[210],n,u,v,vis[210],dis[210];
bool Isin(int x){
if(x < 1 || x > n) return false;
return true;
}
bool bfs(int scr){
queue <int> q;
while(!q.empty()) q.pop();
q.push(scr);
vis[scr] = 1;
while(!q.empty()){
scr = q.front();
q.pop();
if(scr == v) return true;
int upscr = scr + a[scr], downscr = scr - a[scr];
if(!vis[upscr] && Isin(upscr)){
vis[upscr] = 1;
dis[upscr] = dis[scr] + 1;
q.push(upscr);
}
if(!vis[downscr] && Isin(downscr)){
vis[downscr] = 1;
dis[downscr] = dis[scr] + 1;
q.push(downscr);
}
}
return false;
}
int main(){
// freopen("in.txt", "r", stdin);
while(scanf("%d%d%d",&n,&u,&v) == 3 && n){
for(int i=1; i<=n; i++) scanf("%d", &a[i]);
memset(vis, 0, sizeof(vis));
memset(dis, 0, sizeof(dis));
if(!bfs(u)) puts("-1");
else printf("%d\n",dis[v]);
}
return 0;
}