本文主要是介绍给定两个-100到100的整数x和y,对x只能加1,减1,乘2操作,问最少对x进行几次操作能得y,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java解决算法:
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();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()){// System.out.println(q);int temp = q.poll();// System.out.println(temp);//System.out.println(q);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;}
}
这篇关于给定两个-100到100的整数x和y,对x只能加1,减1,乘2操作,问最少对x进行几次操作能得y的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!