Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.
Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.
You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)
Input
First line contains two integers stand for N and M.
Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.
Process to the end of the file.
Output
For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."
Sample Input
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
这道题题目是变型的bfs,队列里记录的是到该地的时间,并不是步数了,步数最好并不代表时间最少,因此同一个地点可能会多次入队列,当然是有条件的,不然就是无限循环了,那条件是什么呢?当然是比前一次入队列更优,也就是时间更少。
那么这样一定会保证解的路径被压入队列的吗?答案也是肯定的。为什么呢?因为从起点到这条路径的任何一个点,也肯定是时间最少的,否则有更优解。也就是满足最优子结构,那么考虑在这条路径上,并且从起点第一个达到的点,这个点显然是在起点周围一圈的点,因此必会均压入队列,因为这是第一次到达这些地方。然后以这个点为起点,继续利用最优子结构,那么很显然这条路径是被压入队列了。
从中我们可以看到,想到了一个算法,不能一下子确定它一定是正确的,需要稍微的证明(当然不需要很严密的数学推导,只需直观推理)。这样不会出现,敲完了程序而WA了,原因是算法错误,大把时间全部浪费了。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#define Maxn 210
using namespace std;
char maze[Maxn][Maxn];
struct point{
int x,y,t;
}q[Maxn*Maxn*10];
int minn[Maxn][Maxn];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int n,m;
const int inf=0x3f3f3f3f;
int bfs(point &sx){
int s=0,e=-1,cur,ans=inf;
q[++e]=sx;
while(s<=e){
point tp=q[s++];
if(maze[tp.x][tp.y]=='a') ans=tp.t;
for(int i=0;i<4;i++){
int tx=tp.x+dx[i],ty=tp.y+dy[i];
if(tx<0||ty<0||tx>=n||ty>=m||maze[tx][ty]=='#') continue;
if(maze[tx][ty]=='x') cur=tp.t+2;
else cur=tp.t+1;
if(cur<minn[tx][ty]){
q[++e]=(point){tx,ty,cur};
minn[tx][ty]=cur;
}
}
}
return ans;
}
int main()
{
point p;
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<n;i++){
getchar();
for(int j=0;j<m;j++){
scanf("%c",&maze[i][j]);
if(maze[i][j]=='r') p=(point){i,j,0};
}
}
memset(minn,0x3f,sizeof minn);
int ans=bfs(p);
if(ans==inf) puts("Poor ANGEL has to stay in the prison all his life.");
else printf("%d\n",ans);
}
return 0;
}