结束后自己试了一下,指通过了10%。思路也是用的BFS,求教给位指出哪里出错了。跪谢。
class Solution {
public:
/**
* 返回最后要输出的答案
* @param n int整型 表示牛牛的数字
* @param m int整型 表示牛妹的数字
* @return int整型
*/
int solve(int n, int m) {
if(n>=m)return n-m;
vector<int>cnt(1005,0);
queue<int>q;
q.push(n);
while(!q.empty()){
int t = q.front();
if(t==m)return cnt[m];
q.pop();
if(t-1>=1 && cnt[t-1]==0){
cnt[t-1]=cnt[t]+1;
q.push(t-1);
}
if(t+1<=m && cnt[t+1]==0){
cnt[t+1]=cnt[t]+1;
q.push(t+1);
}
if(t*t<=1000 && cnt[t*t]==0){
cnt[t*t]=true;
q.push(t*t);
}
}
return cnt[m];
}
};
public:
/**
* 返回最后要输出的答案
* @param n int整型 表示牛牛的数字
* @param m int整型 表示牛妹的数字
* @return int整型
*/
int solve(int n, int m) {
if(n>=m)return n-m;
vector<int>cnt(1005,0);
queue<int>q;
q.push(n);
while(!q.empty()){
int t = q.front();
if(t==m)return cnt[m];
q.pop();
if(t-1>=1 && cnt[t-1]==0){
cnt[t-1]=cnt[t]+1;
q.push(t-1);
}
if(t+1<=m && cnt[t+1]==0){
cnt[t+1]=cnt[t]+1;
q.push(t+1);
}
if(t*t<=1000 && cnt[t*t]==0){
cnt[t*t]=true;
q.push(t*t);
}
}
return cnt[m];
}
};
全部评论
(1) 回帖