bfs,#1T了,求助
查看原帖
bfs,#1T了,求助
816937
Dark_Crown楼主2023/6/2 20:21

本人四格缩进请谅解

#include<bits/stdc++.h>
using namespace std;
long long n,a,b,x[205],vis[205];
struct node{
	int t,h;
};
queue<node>que;
void bfs(){
	bool flag=0;
	node f;
	f.t=0;
	f.h=a;
	que.push(f);
	while(!que.empty()){
		node p=que.front();
		que.pop();
		vis[p.h]=1;
		if(p.h==b){
			cout<<p.t;
			flag=1;
			break;
		}
		node q;
		if(p.h+x[p.h]<=n&&vis[p.h+x[p.h]]==0){
			q.t=p.t+1;
			q.h=p.h+x[p.h];
			que.push(q);
		}
		if(p.h-x[p.h]>=1&&vis[p.h-x[p.h]]==0){
			q.t=p.t+1;
			q.h=p.h-x[p.h];
			que.push(q);
		}
	}
	if(!flag)cout<<"-1";
}
int main(){
	cin>>n>>a>>b;
	for(int i=1;i<=n;i++){
		cin>>x[i];
	}
	bfs();
	return 0;
}
2023/6/2 20:21
加载中...