这题是一道BFS题目,要从终点逆着推起点,需要用上优先队列。
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
int visit[205][205],s[]={1,-1,0,0},t[]={0,0,1,-1},ss,tt,flag,n,m;
char map[205][205];
struct sb
{
int step,x,y;
bool operator<(const sb &t) const
{
return step>t.step;
}
};
priority_queue<sb>q;
int bfs(int xx,int yy)
{
int i;
sb e={0,xx,yy};
visit[xx][yy]=1;
q.push(e);
while(!q.empty())
{
e=q.top();
q.pop();
for(i=0;i<4;i++)
{
ss=e.x+s[i];
tt=e.y+t[i];
if(ss>=1&&ss<=n&&tt>=1&&tt<=m)
{
if(!visit[ss][tt]&&map[ss][tt]=='.')
{
sb e1={e.step+1,ss,tt};
q.push(e1);
visit[ss][tt]=1;
}
else if(!visit[ss][tt]&&map[ss][tt]=='r')
{
flag=1;
break;
}
else if(!visit[ss][tt]&&map[ss][tt]=='x')
{
sb e1={e.step+2,ss,tt};
q.push(e1);
visit[ss][tt]=1;
}
}
}
if(flag==1)
break;
}
while(!q.empty())
q.pop();
return e.step+1;
}
int main()
{
int i,j,xx,yy;
while(cin>>n>>m)
{
memset(map,0,sizeof(map));
memset(visit,0,sizeof(visit));
flag=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='a')
{
xx=i;
yy=j;
}
}
}
int count=bfs(xx,yy);
if(flag==1)
cout<<count<<endl;
else
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
return 0;
}