HDOJ搜索专题之A strange lift
BFS基础题
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 #define N 201 5 #define INF 0x7fffffff 6 using namespace std; 7 queue<int> Q; 8 int d[N],t[N],n,a,b,cur,next; 9 char inq[N]; 10 void bfs() 11 { 12 for(int i=1;i<=n;i++) t[i]=INF; 13 memset(inq,0,sizeof(inq)); 14 t[a]=0; 15 Q.push(a); 16 inq[a]++; 17 while(!Q.empty()) 18 { 19 cur=Q.front(),Q.pop(); 20 inq[cur]--; 21 next=cur+d[cur]; 22 if(next>=1 && next<=n && t[next]>t[cur]+1) 23 { 24 t[next]=t[cur]+1; 25 if(!inq[next]) Q.push(next),inq[next]++; 26 } 27 next=cur-d[cur]; 28 if(next>=1 && next<=n && t[next]>t[cur]+1) 29 { 30 t[next]=t[cur]+1; 31 if(!inq[next]) Q.push(next),inq[next]++; 32 } 33 } 34 if(t[b]==INF) puts("-1"); 35 else printf("%d\n",t[b]); 36 } 37 int main() 38 { 39 while(scanf("%d",&n)&&n) 40 { 41 scanf("%d%d",&a,&b); 42 for(int i=1;i<=n;i++) scanf("%d",&d[i]); 43 bfs(); 44 } 45 return 0; 46 }