DFS题
首先,思想是一个队列,一个数组判楼层是否重复,还有一个楼层数组记录当前楼层数
(我之前把head和楼层混为一谈,导致RE无数遍)
#include<bits/stdc++.h>
using namespace std;
int t[250][3];
int b[250];
bool k[250];//三个数组
int main()
{
int i,j,x,y,n,a,c,head=1,tail=1;
cin>>n>>a>>c;
for (i=1;i<=n;i++)cin>>b[i];
t[1][1]=a;//初始位置
while (t[head][1]!=c)
{
for (i=1;i<=2;i++)
{
if (i==1&&k[t[head][1]+b[t[head][1]]]==0&&t[head][1]+b[t[head][1]]<=250)
{
t[++tail][1]=t[head][1]+b[t[head][1]];
t[tail][2]=t[head][2]+1;
k[t[tail][1]]=1;
}//第一种走法,数组t[tail][1]为当前楼层数,t[tail][2]为当前步骤。
else if (i==2&&k[t[head][1]-b[t[head][1]]]==0&&t[head][1]-b[t[head][1]]>=0)
{
t[++tail][1]=t[head][1]-b[t[head][1]];
t[tail][2]=t[head][2]+1;
k[t[tail][1]]=1;
}
}//第二种走法
head++;
if (head>250){cout<<-1;return 0;}//一定要记得走不到退出!!
}
cout<<t[head][2];
return 0;
}