跳到正文

题解

P1135 奇怪的电梯 题解

Xymsdd_1121约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年8月25日
收录
2025年12月12日
更新
2026年10月17日
篇幅
约 2 分钟
题目
P1135

版本

  1. v2当前
  2. v1

P1135 奇怪的电梯 题目传送门

此题可以用BFS或者DFS做,但是此蒟蒻只会写DFS的,BFS还没学明白,不过这道题用DFS更简便->

思路

每一层有上楼下楼两种选择,判断上楼下楼是否可行,之后递归找到到达楼层b最少的方案

code(加注释)

C++
#include <bits/stdc++.h>
using namespace std;
int k,a1,b1;
int a[205];
int ans[205];
void dfs(int n,int s){
	ans[n]=s;
	int dn=n-a[n];//下楼
	if(dn>=1&&s+1<ans[dn]){//判断是否满足条件
		dfs(dn,s+1);
	}
	dn=n+a[n];//上楼
	if(dn<=k&&s+1<ans[dn]){//同上
		dfs(dn,s+1);
	}
	return ;
}
signed main() {
	ios::sync_with_stdio(0);//好习惯奖励一朵小红花
	cin.tie(0);cout.tie(0);
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	cin>>k>>a1>>b1;
  //求最小值则先赋较大值
	memset(ans,0x3f,sizeof(ans));
	for(int i=1;i<=k;i++){
		cin>>a[i];
	}
	dfs(a1,0);
    //如果大于k证明无法到达,输出-1
	if(ans[b1]>=k) cout<<-1<<"\n";
	else cout<<ans[b1]<<"\n";//好习惯++
	return 0;//完结撒花
}
原文