广度优先遍历

在广度优先遍历中,需要运用到队列,在队列中,才能更快更方便的实现将每一个的可能性遍历到。

下面是一段广搜的模板

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
    int n,num;
}cur,nexxt;
queue<node>qu;
int main()
{
    int n,k,mark[105000],mark1,ans;
    while(~scanf("%d%d",&n,&k))
    {
        if(n==k)
        {
            printf("0\n");
            continue;
        }
        mark1=0;
        memset(mark,0,sizeof(mark));
        while(!qu.empty())
        {
            qu.pop();  //队列清零
        }
        cur.n=n;
        cur.num=0;
        qu.push(cur);
        mark[n]=1;
        while(!qu.empty())
        {
            cur=qu.front();
            qu.pop();
            for(int i=0;i<=2;i++)
            {
                if(i==0)
                nexxt.n=cur.n+1;
                else if(i==1)
                nexxt.n=cur.n-1;
                else if(i==2)
                nexxt.n=cur.n*2;
                nexxt.num=cur.num+1;
                if(nexxt.n<0||nexxt.n>100000) continue;
                if(mark[nexxt.n]==1) continue;
                if(nexxt.n==k)
                {
                    mark1=1;
                    ans=nexxt.num;
                    break;
                }
                mark[nexxt.n]=1;
                qu.push(nexxt);
            }
            if(mark1)
            break;
        }
        printf("%d\n",ans);
    }
    return 0;
}

posted @ 2017-02-28 20:28  ouyang_wsgwz  阅读(131)  评论(0编辑  收藏  举报