HDU2717:Catch That Cow(BFS 队列)

这是一道用队列实现的BFS基础搜索题,学长给我们加这道题主要是让我们联系数据结构里面的队列,话不多说看代码吧。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <queue>
#include <stack>
#define LL long long
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
int vis[100005];
struct node
{
    int x,s;
};
queue<node> q;
int bfs(int N,int K)
{
    while(q.size())
        q.pop();
    node a,t;
    mem(vis);
    a.x=N;
    a.s=0;
    q.push(a);
    vis[N]=1;
    while(q.size())
    {
        a=q.front();
        q.pop();
        if(a.x==K)
            return a.s;
        for(int i=0;i<3;i++)
        {
            if(i==0)
                t.x=a.x+1;
            else if(i==1)
                t.x=a.x-1;
            else
                t.x=a.x*2;
            if(t.x>=0&&t.x<=100000&&!vis[t.x])
            {
                t.s=a.s+1;
                q.push(t);
                vis[t.x]=1;
            }
        }
    }
}
int main()
{
    int N,K;
    scanf("%d%d",&N,&K);
    printf("%d
",bfs(N,K));
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/zznu17-091041/p/8411138.html