我是靠谱客的博主 端庄龙猫,最近开发中收集的这篇文章主要介绍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

题目大意:给出一个矩阵,求从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]!='';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("%dn",q);
else
printf("Poor ANGEL has to stay in the prison all his life.n");
}
return 0;
}

最后

以上就是端庄龙猫为你收集整理的Rescue的全部内容,希望文章能够帮你解决Rescue所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部