渣牛(AWA)POJ-3278

广度优先搜索
使用队列,可以想象成一棵树,
若在任一子结点找到答案,所在深度都是一样的,也就是步数相同
搜寻的方法也理所当然是先左右,再上下,所以使用队列
(标记曾经走的点)

#include<malloc.h>
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define OK 1
#define ERROR 0
typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等
typedef int QElemType;
#define MAXQSIZE 1000 // 最大队列长度(对于循环队列,最大队列长度要减1)

typedef struct
{
   QElemType *base; // 初始化的动态分配存储空间
   int front; // 头指针,若队列不空,指向队列头元素
   int rear; // 尾指针,若队列不空,指向队列尾元素的下一个位置
 }SqQueue;





Status InitQueue(SqQueue &Q)
{
// 构造一个空队列Q,该队列预定义大小为MAXQSIZE
	Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));
	if(!Q.base) exit(1);
	Q.rear=Q.front=0;
	return OK;
}

Status EnQueue(SqQueue &Q,QElemType e)
{
// 插入元素e为Q的新的队尾元素
	 if((Q.rear+1)%MAXQSIZE==Q.front) return ERROR;
	 Q.base[Q.rear]=e;
	 Q.rear=(Q.rear+1)%MAXQSIZE;
	 return OK;
}

Status DeQueue(SqQueue &Q, QElemType &e)
{
// 若队列不空, 则删除Q的队头元素, 用e返回其值, 并返回OK; 否则返回ERROR
	 if(Q.front==Q.rear) return ERROR;
	 e=Q.base[Q.front];
	 Q.front=(Q.front+1)%MAXQSIZE;
	 return OK;
}

Status GetHead(SqQueue Q, QElemType &e)
{
// 若队列不空,则用e返回队头元素,并返回OK,否则返回ERROR
	if(Q.front==Q.rear) return ERROR;
	e=Q.base[Q.front];
	return OK;
}
Status Is_empty(SqQueue Q){
    if(Q.front == Q.rear)
        return 1;
    return 0;
}


int QueueLength(SqQueue Q)
{
// 返回Q的元素个数
	return Q.rear%MAXQSIZE-Q.front%MAXQSIZE;
}

int dp[100010];
int main()
{
    int N,K;
    memset(dp,0,sizeof(dp));
    SqQueue Q;
    QElemType temp;
    InitQueue(Q);
    while(scanf("%d%d",&N,&K)!=EOF){
        EnQueue(Q,N);
        while(!Is_empty(Q)){
            if(N==K){
                printf("0\n");
                break;

            }
            if(dp[K]){
                printf("%d\n",dp[K]);
                break;
            }
            DeQueue(Q,temp);
            //printf("%d\n",temp);
            if(temp!=0&&temp*2<100010&&!dp[temp*2]){
                dp[temp*2] = dp[temp] + 1;
                EnQueue(Q,temp*2);
            }
            if(temp -1 >=0&&!dp[temp -1]){
                dp[temp-1] = dp[temp] +1;
                EnQueue(Q,temp-1);
            }
            if(temp+1>=0&&!dp[temp+1]){
                dp[temp+1] = dp[temp]+1;
                EnQueue(Q,temp+1);
            }
        }

    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值