简单题意
给出一定区域,a代表天使,r代表朋友,#代表墙,.代表路,x代表守卫,只能上下左右四个方向,求出朋友找到天使的最短时间(走一步耗时1,若杀死守卫耗时再加1)
解题思路形成过程
简单的广搜输入数据的时候记录起始和终止的位置,从起始开始四个方向广搜,注意遇到守卫总耗时要加2,直到找到天使为止
感想
渐渐明白了广搜的模式套路。
AC代码
#include <fstream>
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
class data
{
public:
int x,y,cost;
friend bool operator<(data a,data b)
{
return b.cost<a.cost;
}
};
int N,M;
char map[205][205];
int sx,sy,ex,ey;
int xy[4][2]={1,0,-1,0,0,1,0,-1};
int bfs()
{
priority_queue<data>que;
data temp;
temp.x=sx;temp.y=sy;temp.cost=0;
que.push(temp);
map[sx][sy]='#';
while(!que.empty())
{
temp=que.top();
que.pop();
if(temp.x==ex&&temp.y==ey)
return temp.cost;
int fx,fy;
for(int i=0;i<4;i++)
{
fx=temp.x+xy[i][0];
fy=temp.y+xy[i][1];
if(fx>=0&&fx<N&&fy>=0&&fy<M&&map[fx][fy]!='#')
{
data te;
if(map[fx][fy]=='.'||map[fx][fy]=='a'){
te.x=fx;te.y=fy;te.cost=temp.cost+1;
}else{
te.x=fx;te.y=fy;te.cost=temp.cost+2;
}
que.push(te);
map[fx][fy] = '#';
}
}
}
return -1;
}
int main()
{
ifstream cin("in.txt");
while(cin>>N>>M)
{
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
cin>>map[i][j];
if(map[i][j]=='r')
{
sx=i;
sy=j;
}
if(map[i][j]=='a')
{
ex=i;
ey=j;
}
}
}
int ans=bfs();
if(ans==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",ans);
}
return 0;
}