POJ3278 使用BFS解决问题

Poj 3278:

简化题意:

给定两个整数n和k

可以通过三种操作: n+1;n-1 或n*2 ,使得n==k

输出最少的操作次数

 

解题思路:

分两种情况:

当n >= k  直接后退寻找到K

当n <  k 时,采用BFS进行广度优先搜索

// CatchCow.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>

#define MaxLength 200002

int IndexArray[MaxLength] = {0};  //农夫和奶牛的座标点
int moveTime[MaxLength] = {-1};   //到达每个座标需要移动的次数
int tail = 0;
int head = 0;

//init the queue
void initQueue(){
	for(int i = 0;i< MaxLength; i++){
		IndexArray[i] = 0;
		moveTime[i] = -1;
	}
}

//enter the queue
void EnQueue(int number){
	if((tail+1) > MaxLength)
		printf("the queue is full");
	else if((tail+1)<MaxLength){
		IndexArray[tail] = number;
		tail++;
	}
}
//delete from the queue
int DeQueue(){
	if(head == tail)
		printf("the queue is empty");
	int returnValue = IndexArray[head];
	IndexArray[head] = 0;
	head++;
	return returnValue;
}

int main()
{
	int minTime = 0;
	int indexFarmer = 0;
	int indexCow= 0;
	bool findPath = false;
	int tempIndex = 0;

	freopen("test.txt","r",stdin);
	setbuf(stdout,NULL);
	

	//scanf("%d",&indexFarmer);
	//scanf("%d",&indexCow);
	
	while(scanf("%d%d", &indexFarmer, &indexCow) != EOF){
		minTime = 0;
		findPath = false;
		tempIndex = 0;
		initQueue();
    	EnQueue(indexFarmer);
		moveTime[indexFarmer] = 0;
		if(indexFarmer >= indexCow){  //当农夫在奶牛前面时,直接后退找到
			printf("%d\n",(indexFarmer - indexCow));
			continue;
		}
		while(true){
			if(findPath){  //找到最短路径 跳出循环
				printf("%d\n",minTime);
				break;
			}else{
				tempIndex = DeQueue();  //
				if(((tempIndex-1) >= 0) && (moveTime[tempIndex-1] < 0)){ // 首先寻找前移一个座标
					if((tempIndex - 1) == indexCow){
						findPath = true;
						minTime = moveTime[tempIndex]+1;
					}
					else{
						moveTime[tempIndex-1] = moveTime[tempIndex]+1;
						EnQueue(tempIndex-1);
					}
				}
				if((!findPath) && ((tempIndex+1)< MaxLength) && (moveTime[tempIndex+1] < 0)){ //寻找后移一个座标
					if((tempIndex+1) == indexCow){
						findPath = true;
						minTime = moveTime[tempIndex]+1;
					}
					else{
						moveTime[tempIndex+1] = moveTime[tempIndex]+1;
						EnQueue(tempIndex+1);
					}
				}
				if((!findPath)&&((tempIndex*2) < MaxLength) && (moveTime[tempIndex*2] < 0)){ //寻找乘2的座标
					if((tempIndex*2) == indexCow){
						findPath = true;
						minTime = moveTime[tempIndex]+1;
					}
					else{
						moveTime[tempIndex*2] = moveTime[tempIndex]+1;
						EnQueue(tempIndex*2);
					}
				}

			}//else

		}//while(true)
	}//while(scanf)



	return 0;
}
点赞