奇怪的电梯

题目

主要是心血来潮练习广搜才做这道题

算法:广搜
思路:以开头为开始,搜索出的每个节点继续搜索,每个搜索出一个,步数++;直到当前节点为目标层

非queue做法

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int n,a,b;
int m[210];
bool book[210];//标记走过的点防止反复走陷入死循环
struct node{
	int floor;
	int count;
}q[210*210];
int main(){
	//初始化 
	memset(book,0,sizeof(book));
	memset(m,0,sizeof(m));
	cin>>n>>a>>b;
	for(int i=1;i<=n;++i) cin>>m[i];
	if(a==b){
		cout<<"0"<<endl;
		return 0;
	}
	int head=1,tail=2;
	q[head].floor=a;
	q[head].count=0;
	book[a]=1;
	while(head<tail){
	 	//两种情况要么下要么上
	 		
	 		if(q[head].floor==b) break;//达到楼层后退出循环
	 		int flp=m[q[head].floor]+q[head].floor;//向上的情况
	 	
			if(!book[flp] && flp<=n)//当前层数是否是存在的楼层,因为是相加所以不用考虑是否会越下界
			{
				q[tail++].floor=flp;
				q[tail-1].count=q[head].count+1;//步数++
				book[flp]=1;
			}
			int flj=q[head].floor-m[q[head].floor];
		
			if(!book[flj] && flj>=1){//同上 ,因为是相减不用考虑越上界
				q[tail++].floor=flj;
				q[tail-1].count=q[head].count+1;
				book[flj]=1;
			}
		 ++head;//一个点完了扩展下一个点
	}
	if(q[head].floor==b) cout<<q[head].count;//找得到就是输出
	else cout<<"-1";//找不到输出-1;
	return 0;
} 

如果有疑惑,请私信评论、
或者有哪里讲述的有问题也请指出

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值