描述
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
5 17
样例输出
4
大佬用c++写的,我用Java又翻了一遍
http://blog.csdn.net/qq_33193309/article/details/55260780
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class bfs {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
Queue<Integer> que= new LinkedList<>();
int a[]=new int [100001];
for(int i=0;i<100001;i++){
a[i]=100000;
}
a[n]=0;
que.add(n);
while (que.size()!=0){
int num = que.element(); que.remove();
if (num == k)
break;
if (num + 1 <= 100000 && a[num + 1] == 100000) {
a[num + 1] = a[num] + 1;
que.offer(num + 1);
}
if (num - 1 >= 0 && a[num - 1] == 100000){
a[num - 1] = a[num] + 1;
que.offer(num - 1);
}
if (2 * num <= 100000 && a[2 * num] == 100000){
a[2 * num] = a[num] + 1;
que.offer(2 * num);
}
}
System.out.println(a[k]);
}
}