使用BFS搜索每一次操作后的数字以及操作数即可。要注意这道题截止卡的比较死,如果num>m+(abs(m-n))就没有操作的价值了,因为还不如从n一步一步加或减到m。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型 表示牛牛的数字
* @param m int整型 表示牛妹的数字
* @return int整型
*/
//BFS搜索
int solve(int n, int m) {
map<int, int> mp;
mp.clear();
// write code here
queue<int> q;
q.push(n);
mp[n] = 0;
while (q.size()) {
int num = q.front();
q.pop();
if (num==m) {
return mp[num];
}
if (num>m+(abs(m-n))) {
continue;
}
int temp = num-1;
if (mp.find(temp)==mp.end()) {
q.push(temp);
mp[temp] = mp[num]+1;
}
temp = num+1;
if (mp.find(temp)==mp.end()) {
q.push(temp);
mp[temp] = mp[num]+1;
}
temp = num*num;
if (mp.find(temp)==mp.end()) {
q.push(temp);
mp[temp] = mp[num]+1;
}
}
return -1;
}
};

京公网安备 11010502036488号