思路
广搜题,每次遇到满足条件的就加入队列。
代码
#include <bits/stdc++.h>
using namespace std;
struct node{
int now, step;
};
int n, a, b;
int a1[210];
bool vis[210];
queue <node> q1;
int main(){
scanf("%d%d%d", &n, &a, &b);
for(int i = 1; i <= n; i ++) scanf("%d", &a1[i]);
q1.push((node){a,0});
while(!q1.empty()){
node t = q1.front();
q1.pop();
if(t.now == b){
printf("%d", t.step);
return 0;
}
if(t.now - a1[t.now] >= 1 && !vis[t.now - a1[t.now]])
q1.push((node){t.now - a1[t.now], t.step+1}), vis[t.now - a1[t.now]] = 1;
if(t.now + a1[t.now] <= n && !vis[t.now +a1[t.now]])
q1.push((node){t.now + a1[t.now], t.step+1}), vis[t.now + a1[t.now]] = 1;
}
printf("-1");
return 0;
}

本文介绍了一种使用广度优先搜索(BFS)算法解决特定路径寻找问题的方法。通过定义节点结构并利用队列实现广搜过程,每遇到符合条件的节点即加入队列继续探索。该算法用于在一个有限范围内从起始位置A到目标位置B的路径查找。
800

被折叠的 条评论
为什么被折叠?



