这个题要注意边界,例如边界为0,边界超出的100000也不要进队列,否则可能导致数组越界
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n,k;
struct point
{
int x;
int step;
};
queue<point> q;
bool vis[200020];
void bfs(int x)
{
point tmp,hd;
tmp.x=x;
tmp.step=0;
vis[x]=1;
q.push(tmp);
while(!q.empty())
{
hd=q.front();
if(hd.x==k)
{
cout<<hd.step<<endl;
return ;
}
q.pop();
if(!vis[2*hd.x]&&2*hd.x<100005)//一开始没加100005,数组越界了
{
tmp.x=2*hd.x;
tmp.step=hd.step+1;
q.push(tmp);
vis[2*hd.x]=1;
}
if(hd.x>0&&vis[hd.x-1]==0)
{
tmp.x=hd.x-1;
tmp.step=hd.step+1;
q.push(tmp);
vis[hd.x-1]=1;
}
if(!vis[hd.x+1]&&hd.x+1<100005)
{
tmp.x=hd.x+1;
tmp.step=hd.step+1;
q.push(tmp);
vis[hd.x+1]=1;
}
}
}
int main()
{
cin>>n>>k;
memset(vis,0,sizeof(vis));
bfs(n);
}