目前最短题解(2025/7/30)有解析
2025-07-30 15:12:05
发布于:广东
5阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int n,k;
struct node{
int x,time;
};
bool vis[100005]; //访问标记数组
queue<node> q;
void bfs(int a,int b){ //广搜函数
q.push({a,0});
vis[a]=1;
while(!q.empty()){
node l=q.front();
q.pop();
if(l.x==b){
cout<<l.time;
return;
}
for(int i=0;i<3;i++){
int d[]={-1,1,l.x};
int nd=l.x+d[i];
if(!vis[nd]){ //确认未访问过
vis[l.x]=1; //标记访问过,防止重复访问导致死循环
q.push({nd,l.time+1});
}
}
}
}
int main(){
cin>>n>>k;
bfs(n,k);
return 0;
}
这里空空如也
有帮助,赞一个