BFS基础框架题,写在这里只是为了让大家对于BFS有个更好的理解
对于我也是,我一开始也不知道BFS和DFS能做些什么,只知道可以用来走迷宫,发现还是蛮有趣的,现在更加有趣了。
这道题目很容易理解,给你两个数,三种操作,问N是否能通过这三种操作将N变成K.
看着数据量暴力肯定超时,所以当时直接就想到了BFS,
的确BFS是蛮快的,但是费内存(果然,一开始没有写一个数组用于标记是否某个数已经被到达过...果然队列爆了= =)
下面是代码,还是蛮好理解的
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
const int maxn=100001;
bool vis[maxn];
struct node
{
int x;
int step;
}now,next;
int n,k;
int bfs()
{
queue<node> q;
now.x=n;
now.step=0;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<3;i++)
{
if(i==0)
{
next.x=now.x+1;
next.step=now.step+1;
}
else if(i==1)
{
next.x=now.x-1;
next.step=now.step+1;
}
else
{
next.x=now.x*2;
next.step=now.step+1;
}
if(next.x>maxn||next.x<0)
continue;
if(!vis[next.x])
{
q.push(next);
vis[next.x]=1;
}
if(next.x==k)
return next.step;
}
}
return -1;
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
memset(vis,0,sizeof vis);
if(n>=k)
printf("%d\n",n-k);
else
printf("%d\n",bfs());
}
return 0;
}