地址:
点击打开链接
这个题,我wa了一次,后来检查了好久,才发现必须考虑一个情况,就是他自己一开始就在目标楼层,因此需要稍微调整一下以前写bfs的判断结束的位置。代码如下
#include <iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
#define MAX 201
struct Person
{
int now;
int time ;
friend bool operator <(Person a ,Person b)
{
return a.time>b.time;
}
};
int d[2*MAX];
int vis[2*MAX];
int high ,from,to;
bool inBuilding(int x){
if(x<1||x>high)
{
return false ;
}
return true ;
}
int BFS(int start,int target ){
memset(vis,0,sizeof(vis));
Person now ;
now.now= start;
now.time = 0;
priority_queue<Person> q ;
Person next ;
vis[start]=1;
q.push(now);
while(!q.empty())
{
now = q.top();
q.pop();
if(now.now == target)
{
return now.time ;
}
// cout <<"??"<<endl;
for(int i =0 ; i <2 ; i ++)
{
if(i==0)
{
next.now = now.now+d[now.now-1] ;
}else {
next.now = now.now-d[now.now-1] ;
}
if(inBuilding(next.now)&&vis[next.now]!=1)
{
/*if(next.now == target)
{
return now.time+1;
}*/
vis[next.now]=1;
next.time = now.time+1;
// cout << next.time << " x " << next.now<< endl;
q.push(next);
}
}
}
return -1 ;
}
int main(){
while(cin>> high&&high!=0)
{
cin >>from>>to;
for(int i = 0 ; i <high ; i ++)
{
cin>>d[i];
}
cout <<BFS(from,to)<<endl;
}
}
本文详细介绍了使用BFS(宽度优先搜索)算法解决实际问题的过程,并通过一个具体的例子展示了如何调整算法以处理特殊情况,例如起始位置即为目标位置的情况。文章提供了完整的代码实现,并解释了关键步骤。
394

被折叠的 条评论
为什么被折叠?



