写道题:给定两个-100到100的整数x和y,对x只能加1,减1,乘2操作,问最少对x进行几次操作能得y
import java.util.*;
public class A{
public static void main(String[] agrs){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
scan.close();
int count = minOp(n,m) - 1;
System.out.println(count);
}
public static int minOp(int n, int m){
int[] visited = new int[10000];
Queue<Integer>q =new LinkedList <Integer>() ;
q.offer(n);
visited[n] = 1;
while (!q.isEmpty()){
int temp = q.poll();
if (temp == m)
return visited[m];
//关键步骤
if (temp + 1 <= m && visited[temp + 1] == 0){
q.offer(temp + 1);
visited[temp + 1] = visited[temp] + 1;
}
if ( temp - 1 >= 0 && temp - 1 <= m && visited[temp - 1] == 0){
q.offer(temp - 1);
visited[temp - 1] = visited[temp] + 1;
}
if (temp * 2 <= m && visited[temp * 2] == 0){
q.offer(temp * 2);
visited[temp * 2] = visited[temp] + 1;
}
}
return 0;
}
}