题目大意就是给你一个字符矩阵,找出r到达a的需要使用的最短时间。没走一步花掉单位1的时间,如果进过x,就多花费单位1的时间。如果r无法达到a,输出"Poor ANGEL has to stay in the prison all his life.",否则,输出最短的时间。
对就类似于迷宫类题目,直接使用bfs搜索,但是由于需要最短的时间,所以需要使用优先队列保存节点。直接使用stl库里面的priority_queue,当然,也可以自己写一个优先队列。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=205;
const int INF=1<<30;
int ans;
int n,m;
struct node
{
int r,c;
int t;
bool operator < (const node &a)const
{
return a.t<t;
}
};
char mp[maxn][maxn];
bool vis[maxn][maxn];
int dr[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool bfs(int x,int y)
{
priority_queue<node> que;
node now;
now.r=x;
now.c=y;
now.t=0;
vis[x][y]=true;
que.push(now);
while(!que.empty())
{
now=que.top();
que.pop();
for(int i=0;i<4;i++)
{
node tmp;
tmp.r=now.r+dr[i][0];
tmp.c=now.c+dr[i][1];
tmp.t=now.t;
if(tmp.r>0 && tmp.r<=n && tmp.c>0 && tmp.c<=m)
{
if(vis[tmp.r][tmp.c])continue;
if(mp[tmp.r][tmp.c]=='r')
{
ans=tmp.t+1;
return true;
}
if(mp[tmp.r][tmp.c]=='.')
{
tmp.t++;
que.push(tmp);
vis[tmp.r][tmp.c]=true;
}
if(mp[tmp.r][tmp.c]=='x')
{
tmp.t+=2;
que.push(tmp);
vis[tmp.r][tmp.c]=true;
}
}
}
}
return false;
}
void init()
{
ans=INF;
memset(vis,false,sizeof(vis));
}
void solve(int x,int y)
{
init();
if(bfs(x,y))
{
printf("%d\n",ans);
}
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main()
{
int x,y;
// freopen("in.txt","r",stdin);
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
scanf("%s",mp[i]+1);
bool isf=false;
for(int i=1;i<=n && !isf;i++)
for(int j=1;j<=m;j++)
if(mp[i][j]=='a')
{
x=i;
y=j;
isf=true;
break;
}
solve(x,y);
}
return 0;
}