Rescue
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
#include<stdio.h>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
char maze[200][201]; //地图面积
int N,M; //行数 列数
int sx,sy; //起点坐标
int gx,gy; //终点坐标
bool isv[200][201]; //是否访问过
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1}; //四个方向
struct node{
int x,y;
int step;
friend bool operator < (node a,node b){
//自定义优先级
return a.step >b.step; //从小到大排序
}
};
int bfs(){
memset(isv,0,sizeof(isv)); //将isv初始化为false
priority_queue <node> que; //优先队列
node now,next;
now.x = sx; now.y = sy; //将起点坐标给now
now.step = 0; //起点位置步数为0
isv[sx][sy] = true; //将起点位置标记为已访问
que.push(now); //导入起点坐标
while(que.size()){ ///第一次的话
now = que.top(); que.pop();
///将起始坐标给now,然后将这个坐标弹出
if(now.x==gx &&now.y==gy) //到达终点 就返回step
return now.step;
for(int i = 0;i<4;i++){
//四个方向遍历
int nx = now.x + dx[i];
int ny = now.y + dy[i];
if(0<=nx&&nx<N&&0<=ny&&ny<M&&maze[nx][ny]!='#'&&isv[nx][ny]==0){
//该点在地图内且不是墙,也还没有被访问过
next.x = nx; next.y = ny; //那next就为该点
if(maze[nx][ny]=='x')
next.step = now.step + 2;
else
next.step = now.step + 1;
isv[nx][ny] = 1;
que.push(next);
//优先对列 第一个总是最小路程的
}
}
}
return -1;
}
int main(){
while(scanf("%d%d",&N,&M)!=EOF){
for(int i = 0;i<N;i++){
scanf("%s",&maze[i]);
for(int j = 0;j<M;j++){
if(maze[i][j]=='a'){
gx = i; gy = j;
}
if(maze[i][j]=='r'){
sx = i; sy = j;
}
}
}
int res = bfs();
if(res!=-1)
printf("%d\n",res);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}