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.)
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.
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."
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
13
题目大意:给出一个矩阵,求从r到a的最短路径,经过x时间花费时间为2,经过.时间花费时间为1。需要注意的是,r在图中可能有多个。
解题思路:因r可能有多个,为避免错误,从a开始找最近的r即可。用优先队列进行搜索查找最短路径。
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
typedef struct stu{
int x,y,z;
friend bool operator < (stu a,stu b)
{
return a.z>b.z;
}
}st;
int main()
{
int i,j,m,n,x1,y1,flag,q;
char a[210][210];
int b[4][2]={1,0,0,1,0,-1,-1,0};
priority_queue<st> s;
st v,k;
while(scanf("%d%d",&m,&n)!=EOF)
{
q=0;flag=0;
memset(a,0,sizeof(a));
for(i=0;i<m;i++)
{
scanf("%s",a[i]);
for(j=0;a[i][j]!='\0';j++)
{
if(a[i][j]=='a')
{
x1=i;y1=j;
}
}
}
a[x1][y1]='#';
v.x=x1;v.y=y1;
v.z=0;
s.push(v);
while(!s.empty())
{
int nx,ny;
k=s.top();
s.pop();
for(i=0;i<4;i++)
{
nx=k.x+b[i][0];
ny=k.y+b[i][1];
if(a[nx][ny]=='#'||nx<0||ny<0||nx>=m||ny>=n)
continue;
else
{
if(a[nx][ny]=='.')
{
a[nx][ny]='#';
v.x=nx;v.y=ny;
v.z=k.z+1;
s.push(v);
}
if(a[nx][ny]=='x')
{
a[nx][ny]='#';
v.x=nx;v.y=ny;
v.z=k.z+2;
s.push(v);
}
if(a[nx][ny]=='r')
{
flag=1;
q=k.z+1;
break;
}
}
}
if(flag==1)
break;
}
while(!s.empty())
s.pop();
if(flag==1)
printf("%d\n",q);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}