题意:r->a用时最少,经过'x'需2s,经过'.'1s.
思路:用BFS,但是,显然,走的步数少并不代表用的时间少。因此,标记走到每个点用的最少时间,若下次要走到该点,必须比该点用时更少(同时更新该点)。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <string.h>
#include <map>
#include <set>
using namespace std;
#define maxn 100005
#define inff 1000000000
char mat[205][205];
int n,m,stx,sty,enx,eny,mins;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node {
int x,y,step;
}tx,ty;
int v[205][205];
void bfs()
{
queue<node>q;
tx.x=stx;
tx.y=sty;
tx.step=0;
q.push(tx);
while(!q.empty())
{
tx=q.front();
q.pop();
if(tx.x==enx&&tx.y==eny)
{
mins=min(tx.step,mins);
continue;
}
for(int i=0;i<4;i++)
{
ty.x=tx.x+dir[i][0];
ty.y=tx.y+dir[i][1];
if(ty.x>=0&&ty.x<n&&ty.y>=0&&ty.y<m&&mat[ty.x][ty.y]!='#')
{
if(mat[ty.x][ty.y]=='x')
{
ty.step=tx.step+2;
if(ty.step<v[ty.x][ty.y])
{
v[ty.x][ty.y]=ty.step;
q.push(ty);
}
}
else if(mat[ty.x][ty.y]=='.'||mat[ty.x][ty.y]=='a')
{
ty.step=tx.step+1;
if(ty.step<v[ty.x][ty.y])
{
v[ty.x][ty.y]=ty.step;
q.push(ty);
}
}
}
}
}
if(mins<inff)
cout<<mins<<endl;
else cout<<"Poor ANGEL has to stay in the prison all his life.\n";
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
for(i=0;i<n;i++)
{
scanf("%s",mat[i]);
for(j=0;j<m;j++)
{
if(mat[i][j]=='r')
{
stx=i;
sty=j;
}
if(mat[i][j]=='a')
{
enx=i;
eny=j;
}
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
v[i][j]=inff;
}
mins=inff;
bfs();
}
return 0;
}