相比于POJ2251的三维BFS,这道题做法思路完全相同且过程更加简单,也不需要用结构体,check只要判断vis和左右边界的越界情况就OK。
记得清空队列,其他没什么好说的。
#include<iostream> #include<queue> #include<cstring> #include<cstdio> using namespace std; const int maxn=100001; bool vis[maxn]; int step[maxn]; queue <int> q; int bfs(int n,int k) { int head,next; q.push(n); step[n]=0; vis[n]=true; while(!q.empty()) { head=q.front(); q.pop(); for(int i=0;i<3;i++) { if(i==0) next=head-1; else if(i==1) next=head+1; else next=head*2; if(next<0 || next>=maxn) continue; if(!vis[next]) { q.push(next); step[next]=step[head]+1; vis[next]=true; } if(next==k) return step[next]; } } } int main() { int n,k; while(cin>>n>>k) { memset(step,0,sizeof(step)); memset(vis,false,sizeof(vis)); while(!q.empty()) q.pop(); if(n>=k) printf("%d ",n-k); else printf("%d ",bfs(n,k)); } return 0; }