Catch That Cow --bfs

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input
Line 1: Two space-separated integers:  N and  K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4

分析:最值问题一般使用bfs解决,这个题只要把题目中人所能走的方案逐个尝试就好了

import java.util.*;

public class Main {
    static Scanner in = new Scanner(System.in);
    static int MAXN = 200000;
    static boolean[] vis= new boolean[MAXN];
    static int n,k;
    static int bfs(){
      Queue <Node> q = new LinkedList<Node>();
       q.clear();
      Node in = new Node(n, 0);
        vis[n]=true;
       q.add(in);
      while(!q.isEmpty()){
    	  Node te = q.poll();
    	  if(te.x==k)
    		 return te.step;   	  
    	 for(int i=0;i<3;i++){//尝试每个方案
    	    Node nw = new Node();
    		 if(i==0)
    			 nw.x=te.x-1;
    		 else if(i==1)
    			 nw.x=te.x+1;
    		 else if(i==2)
    			 nw.x=te.x*2;
    		 if(nw.x<=MAXN&&nw.x>=0&&!vis[nw.x]){//剪枝优化
    			 vis[nw.x]=true;
    			 nw.step=te.step+1;
    			 q.add(nw);
    		 }
    	  }
      }
      return 0;
    }
	public static void main(String[] args) {
		  n = in.nextInt();
		  k = in.nextInt();	
		  Arrays.fill(vis,false);
          int ans=0;
		  ans=bfs();			
		System.out.println(ans);
  }
}
class Node {
	int x;
	int step;
	Node(){};
	Node(int x,int step){
		this.x=x;
		this.step=step;
	}
}
分析:搜索题对于问题的状态脑子里面要形成一棵清晰的树,每一步的状态先用自己的思路进行构建树的状态,再去写搜索的具体实现。

这个题也是绝了,我一开始在for循环外面初始化的一个新的node,然后往队列里面添加,其实每次都只是添加了一个对象啊,我真是蠢死了,这种错误也范,可能是因为和C语言搞混了吧。。。。

所以,切记Java里面要使用新的对象就要new一个,当然可以使用引用赋值来取值,但是要存储不同的值要进行new.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值