注解
1、广度优先遍历BFS,注意使用visit数组记录访问过的层数,否则会报内存溢出。
代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 201;
int A, B, N;
int visit[MAXN];
int a[MAXN];
struct Node{
int f;
int step;
};
int bfs(){
queue<Node> q;
Node node;
node.f = A;
node.step = 0;
q.push(node);
while(q.size()>0){
Node top = q.front();
q.pop();
if(top.f==B){
return top.step;
}
else{
int step = top.step+1;
int next1 = top.f + a[top.f];
int next2 = top.f - a[top.f];
if(visit[next1]==0 && next1<=N){
Node tmp;
tmp.f = next1;
tmp.step = step;
q.push(tmp);
visit[next1] = 1;
}
if(visit[next2]==0 && next2>=1){
Node tmp;
tmp.f = next2;
tmp.step = step;
q.push(tmp);
visit[next2] = 1;
}
}
}
return -1;
}
int main(){
scanf("%d", &N);
while(N){
memset(visit, 0, sizeof(visit));
memset(a, 0, sizeof(a));
scanf("%d %d", &A, &B);
for(int i=1; i<=N; i++){
scanf("%d", &a[i]);
}
int ans = bfs();
printf("%d\n", ans);
scanf("%d", &N);
}
return 0;
}