首页 > 代码库 > bfs Catch That Cow

bfs Catch That Cow

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
#define maxn 100001
int steps=0;
int book[maxn]={0};
queue<int>q;
void bfs(int a,int b)
{
    memset(book,0,sizeof(book));
    book[a]=1;
    while(!q.empty())
        q.pop();
    q.push(a);
    while(!q.empty())
    {
        int q_size=q.size();
        while(q_size--)
        {
            int head=q.front();
            q.pop();
            if(head==b) return;
            int t=0;
            for(int i=1;i<=3;i++)
            {
                if(i==1) t=head-1;
                else if(i==2) t=head+1;
                else if(i==3) t=2*head;
                if(t<0||t>maxn)
                    continue;
                if(!book[t])
                {
                    book[t]=1;
                    q.push(t);
                }
            }
        }
        steps++;
    }

}
int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    if(n>=k)
        printf("%d\n",n-k);
    else
    {
        bfs(n,k);
        printf("%d\n",steps);
    }
    return 0;
}

  

bfs Catch That Cow