bfs 64分求调 QAQ
查看原帖
bfs 64分求调 QAQ
1362554
monologues楼主2024/7/13 21:31
#include<bits/stdc++.h>
using namespace std;
int a[209],v[209],n,a1,a2;
struct S{
	int x;
	int step;
}s1,s2;
queue<S>q;
void bfs()
{
	while(!q.empty())q.pop();
	q.push({a1,0});
	v[a1]=1;
	while(!q.empty())
	{
		 s1=q.front();
		 q.pop();
		 if(s1.x==a2)
		 {
		   cout<<s1.step;
		   return;
		 }
		if(s1.x+a[s1.x]>0&&s1.x+a[s1.x]<=n&&v[s1.x+a[s1.x]]==0)
		{
		  v[s1.x]=1;
		  q.push({s1.x+a[s1.x],s1.step+1});
		}
		if(s1.x-a[s1.x]>0&&s1.x-a[s1.x]<=n&&v[s1.x-a[s1.x]]==0)
		{
		  v[s1.x]=1;
		  q.push({s1.x-a[s1.x],s1.step+1});
		}
	}
	cout<<-1;
}
int main()
{
	cin>>n>>a1>>a2;
	for(int i=1;i<=n;i++)cin>>a[i];
	bfs();
	return 0;
}
2024/7/13 21:31
加载中...