典型的 bfs 分层次搜索,数字问题无边界dfs肯定超时
注意bfs没有取消标记这一操作、
防止越界的判断语句 往前放,
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 100010
#define inf 0x3f3f3f3f
struct node
{
int x,step;
} temp,temp2;
int n,k,ans;
void bfs()
{
bool vis[maxn]= {0};
queue<node>q;
temp.x=n;
temp.step=0;
q.push(temp);
vis[temp.x]=1;
while(!q.empty())
{
temp.x=q.front().x;
temp.step=q.front().step;
q.pop();
if(temp.x==k)
{
ans=temp.step;
return ;
}
if(temp.x+1>=0)
{
if(!vis[temp.x+1]&&temp.x+1<maxn-2)
{
temp2.x=temp.x+1;
temp2.step=temp.step+1;
vis[temp2.x]=1;
q.push(temp2);
}
}
if(temp.x-1>=0)
{
if(!vis[temp.x-1])
{
temp2.x=temp.x-1;
temp2.step=temp.step+1;
vis[temp2.x]=1;
q.push(temp2);
}
}
if(temp.x*2<maxn)
{
if(!vis[temp.x*2])
{
temp2.x=temp.x*2;
temp2.step=temp.step+1;
vis[temp2.x]=1;
q.push(temp2);
}
}
}
}
int main()
{
cin>>n>>k;
bfs();
cout<<ans<<endl;
}