题目描述
题意:
一天,牛妹找牛牛做一个游戏,牛妹给牛牛写了一个数字n,然后又给自己写了一个数字m,她希望牛牛能执行最少的操作将他的数字转化成自己的。
操作共有三种,如下:
1.在当前数字的基础上加一,如:4转化为5
2.在当前数字的基础上减一,如:4转化为3
3.将当前数字变成它的平方,如:4转化为16
你能帮牛牛解决这个问题吗?
输入:
给定n,m,分别表示牛牛和牛妹的数字。
输出:
返回最少需要的操作数。
示例1
输入:3,10
输出:2
备注:
(1≤n,m≤1000)
思路:广搜法(bfs)
注意剪枝:
1、遍历到的值已超出1024/已低于0;
2、遍历到的值已出现过,后遍历到一定比先遍历到的情况所需的操作数更多
import java.util.*;
class Pair{
int n;
int res;
Pair(int n,int res){
this.n=n;
this.res=res;
};
}
public class Solution {
/**
* 返回最后要输出的答案
* @param n int整型 表示牛牛的数字
* @param m int整型 表示牛妹的数字
* @return int整型
*/
public int solve (int n, int m) {
// write code here
if(n>=m)return n-m;
int[] a=new int[1100];
ArrayDeque<Pair> ad=new ArrayDeque<>();
ad.add(new Pair(n,0));
while(!ad.isEmpty()){
Pair now=ad.pollFirst();
if(now.n==m)return now.res;
if(now.n>1024||now.n<0||a[now.n]!=0)continue;//剪枝
a[now.n]=1;//表明该值已出现过
ad.add(new Pair(now.n+1,now.res+1));
ad.add(new Pair(now.n-1,now.res+1));
ad.add(new Pair(now.n*now.n,now.res+1));
}
return -1;
}
}