迷路的小猫(广度优先搜索)
2024-07-28 17:13:38
发布于:北京
#include<bits/stdc++.h>
using namespace std;
int n,k,vis[1000005];
struct node{
int x,step;
};
void dfs(){
queue<node>q;
q.push((node){n,0});
vis[n]=1;
while(!q.empty()){
node n1=q.front();
q.pop();
if(n1.x==k){
cout<<n1.step;
return;
}
if(n1.x+1<=100000&&vis[n1.x+1]==0){
vis[n1.x+1]=1;
q.push((node){n1.x+1,n1.step+1});
}
if(n1.x-1<=100000&&vis[n1.x-1]==0){
vis[n1.x-1]=1;
q.push((node){n1.x-1,n1.step+1});
}
if(n1.x*2<=100000&&vis[n1.x*2]==0){
vis[n1.x*2]=1;
q.push((node){n1.x*2,n1.step+1});
}
}
}
int main(){
cin>>n>>k;
dfs();
return 0;
}
[链接描述](https://www.acgo.cn/problemset/info/19382?homeworkId=1492&teamCode=1768162775202656256)
这里空空如也
有帮助,赞一个