奇怪的电梯

题目

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

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

非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;
} 

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

posted @ 2021-02-01 19:19  归游  阅读(19)  评论(0编辑  收藏  举报