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;
}
}

本文介绍了一个Java实现的算法,用于计算从一个整数转换到另一个整数所需的最小操作次数。操作包括加1、减1和乘2。通过使用广度优先搜索算法,并利用队列和访问数组,该算法能够有效地找到最短路径。
2703

被折叠的 条评论
为什么被折叠?



