题意
- 把数字n变为数字m,可以进行如下三种操作:+1,-1,平方,问最少需要几步
思路
- bfs每一步的所有可能,记录一个数最早出现的时间
- 对于步数:最大不会超过n-m步(从n不断+1变为m),同理,如果平方后的数大于等于2m-n,说明减回m的步数一定比从n加到m还多,直接舍去
int solve(int n, int m) {
// write code here
if(n==m)return 0;
int stp[10000]={0};
queue<int>q;
q.push(n);
while(q.size()){
int now=q.front();
q.pop();
if(now==m)return stp[m];
if(stp[now-1]==0){q.push(now-1);stp[now-1]=stp[now]+1;}
if(stp[now+1]==0){q.push(now+1);stp[now+1]=stp[now]+1;}
if(now*now<=2*m-n&&stp[now*now]==0){q.push(now*now);stp[now*now]=stp[now]+1;}
}
return -1;
}