BFS之抓住那头牛

建立对应的表

在这里插入图片描述

核心思想

在这里插入图片描述

代码实现

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxsize = 100000;
const int MaxN = 1000000;
struct Step{
    
    
	int x;//位置
	int step;//步数
	Step(int xx,int s):x(xx),step(s) {
    
    }
};
int visited[MaxN];
int N,K;
queue <Step> q;//open表
void BFS(int x,int step){
    
    
	q.push(Step(x,step));
	visited[x] = 1;
	while(!q.empty()){
    
    
		Step temp = q.front();
		if(temp.x == K){
    
    
			printf("%d\n",temp.step);
			return ;
		}else{
    
    
			if(!visited[temp.x + 1] && temp.x + 1 <= maxsize){
    
    
				visited[temp.x + 1] = 1;
				q.push(Step(temp.x + 1,temp.step+1));
			}
			if(!visited[temp.x-1] && temp.x-1 >= 0){
    
    
				visited[temp.x - 1] = 1;
				q.push(Step(temp.x - 1,temp.step+1));
			}
			if(!visited[2 * temp.x] && 2 * temp.x <= maxsize){
    
    
				visited[2 * temp.x] = 1;
				q.push(Step(2 * temp.x,temp.step + 1));
			}
			q.pop();
		}	
	}	
}
int main(){
    
    
	scanf("%d%d",&N,&K);
	memset(visited,0,sizeof(visited));
	BFS(N,0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wuyvle/article/details/113596778