题解 | 奇怪的电梯
2025-05-21 19:39:02
发布于:北京
2阅读
0回复
0点赞
原题链接A8051 奇怪的电梯
bfs板子,用bfs层级遍历,求最短路
#include <bits/stdc++.h>
using namespace std;
int n,a,b,k[300];
bool vis[300];
int dx[] = {1,-1};
//记录走过的点
struct node{
int x;
int step;
};
//bfs模版
int bfs(int sx,int ex){
//标记首点
queue<node> q;
q.push({sx,0});
vis[sx] = 1;
//层级遍历
while(!q.empty()){
node now = q.front();
q.pop();
if(now.x == ex) return now.step;
for(int i = 0;i < 2;i ++){
int nx = now.x + k[now.x] * dx[i];
if(nx < 1 || nx > n) continue;
if(vis[nx]) continue;
vis[nx]= 1;
q.push({nx,now.step+1});
}
}
//失败
return -1;
}
int main(){
cin >> n >> a >> b;
for(int i = 1;i <= n;i ++)
cin >> k[i];
cout << bfs(a,b);
}
这里空空如也
有帮助,赞一个