呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼上有一个数字Ki,电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。从1楼开始。在1楼,按“上”可以到4楼,按“下”是不起作用的,因为没有−2楼。那么,从A楼到B楼至少要按几次按钮呢?
dfs
#include<bits/stdc++.h>
using namespace std;
int n,a[100001],end,ans=999999999,book[100001];
void dfs(int x,int t)
{
if(x==end)
{
ans=min(ans,t);
return;
}
if(t>ans)
return ;
if(x-a[x]>0&&!book[x-a[x]]) book[x-a[x]]=1,dfs(x-a[x],t+1),book[x-a[x]]=0;
if(x+a[x]<=n&&!book[x+a[x]]) book[x+a[x]]=1,dfs(x+a[x],t+1),book[x+a[x]]=0;
}
int main()
{
int i,sta;
cin>>n>>sta>>end;
for(i=1;i<=n;i++)
cin>>a[i];
book[sta]=1;
dfs(sta,0);
if(ans==999999999)
cout<<"-1"<<endl;
else
cout<<ans<<endl;
return 0;
}
bfs
#include<bits/stdc++.h>
using namespace std;
typedef struct point
{
int x,t;
}P;
queue<P> q;
P now,temp;
int main()
{
int n,sta,end,i,j,a[100001],book[100001]={0};
cin>>n>>sta>>end;
for(i=1;i<=n;i++)
cin>>a[i];
P start={sta,0};
book[sta]=1;
q.push(start);
while(!q.empty())
{
now=q.front();
if(now.x==end)
break;
if(now.x+a[now.x]<=n&&book[now.x+a[now.x]]==0)
{
book[now.x+a[now.x]]=1;
temp={now.x+a[now.x],now.t+1};
q.push(temp);
}
if(now.x-a[now.x]>0&&book[now.x-a[now.x]]==0)
{
book[now.x-a[now.x]]=1;
temp={now.x-a[now.x],now.t+1};
q.push(temp);
}
q.pop();
}
if(now.x==end)
cout<<now.t<<endl;
else
cout<<"-1"<<endl;
return 0;
}