POJ-3278:BFS简单模板题

题目链接

思路:每个节点可以继续发出三个节点,放入队列,依次搜查即可
该题亦可用DFS做
下面是BFS的AC代码:

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
#define inf 3f3f3f3f
#define N 100000+10
ll n,k,vis[N],d[N];
bool judge(ll x)
{
    if(x>=0&&x<=100000) return true;
    return false;
}
void bfs()
{
    queue<ll> q;
    vis[n]=1;
    d[n]=0;
    q.push(n);
    while(!q.empty())
    {
        ll tmp=q.front();
        q.pop();
        if(tmp==k)
        {
            cout<<d[tmp]<<endl;
            return ;
        }
        ll x;
        x=tmp+1;
        if(judge(x)&&!vis[x])
        {
            q.push(x);
            d[x]=d[tmp]+1;
            vis[x]=1;
        }
        x=tmp-1;
        if(judge(x)&&!vis[x])
        {
            q.push(x);
            d[x]=d[tmp]+1;
            vis[x]=1;
        }
        x=tmp*2;
        if(judge(x)&&!vis[x])
        {
            q.push(x);
            d[x]=d[tmp]+1;
            vis[x]=1;
        }
    }
}
int main()
{
 while(cin>>n>>k)
 {
 if(n>k)
 {
 cout<<n-k<<endl;
 continue;
 }
 bfs();
 }
}

你可能感兴趣的:(DFS,BFS)