题解
2024-05-07 12:46:35
发布于:广东
11阅读
0回复
0点赞
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct node{
int val, step;
};
int a[1005];
bool vis[1005];
int n, m, k;
int bfs(){
queue <node> q;
q.push({m, 0});
while(!q.empty()){
node head = q.front();
q.pop();
if(head.val == k) return head.step;
if(!vis[head.val + a[head.val]] && head.val + a[head.val] <= n){//向上走
vis[head.val + a[head.val]] = 1;
q.push({head.val + a[head.val], head.step + 1});
}if(!head.val - a[head.val] && head.val - a[head.val] > 1){//向下走
vis[head.val - a[head.val]] = 1;
q.push({head.val - a[head.val], head.step + 1});
}
}return -1;
}
int main(){
cin >> n >> m >> k;
for(int i = 1; i <= n; i++){
cin >> a[i];
}cout << bfs();
return 0;
}
时间复杂度:
这里空空如也
有帮助,赞一个