import java.util.*;
public class Main{
static boolean[] vis = new boolean[100005];
static int n;
static int k;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
bfs();
}
public static void bfs(){
Queue<POS> q = new LinkedList<>();
q.offer(new POS(n,0));
vis[n] = true;
while (!q.isEmpty()){
POS now = q.poll();
int now_position = now.position;
int now_time = now.time;
if(now_position == k){
System.out.println(now_time);
break;
}
int next_position = now_position+1;
int next_time = now_time+1;
if(check(next_position)){
vis[next_position] = true;
q.offer(new POS(next_position,next_time));
}
next_position = now_position-1;
next_time = now_time+1;
if(check(next_position)){
vis[next_position] = true;
q.offer(new POS(next_position,next_time));
}
next_position = now_position*2;
next_time = now_time+1;
if(check(next_position)){
vis[next_position] = true;
q.offer(new POS(next_position,next_time));
}
}
}
public static boolean check(int x){
if(x >= 0 && x <= 100000 && vis[x] == false){
return true;
}
return false;
}
}
class POS{
int position;
int time;
public POS(int position, int time) {
this.position = position;
this.time = time;
}
}
试题名称 算法提高 逃跑的牛 Java(BFS)
最新推荐文章于 2023-04-16 22:53:18 发布