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 X - 1 or X + 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?
5 17
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.