您的位置:首页 > 产品设计 > UI/UE

【HDU】-1242-Rescue(BFS+优先队列)

2016-07-29 21:04 351 查看


Rescue

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 26500    Accepted Submission(s): 9380


Problem Description

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 是守卫。走路 1 秒,打守卫 2 秒,求到 a 最小值。

题解:用到优先队列,步数少的优先考虑。

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
char a[220][220];
int vis[220][220];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int n,m,stx,sty,edx,edy;
struct node
{
int stxx,styy,step;
bool friend operator < (node x,node y)
{
return x.step>y.step; //优先考虑步数少的
}
}pr,ne;
bool dis(node x)
{
if(x.stxx<1||x.stxx>n||x.styy>m||x.styy<1||vis[x.stxx][x.styy]==1||a[x.stxx][x.styy]=='#')
return false;
return true;
}
int bfs()
{
priority_queue<node> q;
pr.stxx=stx;
pr.styy=sty;
pr.step=0;
q.push(pr);
vis[pr.stxx][pr.styy]=1;
while(!q.empty())
{
pr=q.top();
q.pop();

for(int i=0;i<4;i++)
{
ne=pr;
ne.stxx+=dx[i];
ne.styy+=dy[i];
if(!dis(ne))
continue;
if(ne.stxx==edx&&ne.styy==edy) //和终点相同就返回步数
return ne.step+1;
if(a[ne.stxx][ne.styy]=='x') //打人 +2
ne.step+=2;
else
ne.step++; //走路 +1
q.push(ne);
vis[ne.stxx][ne.styy]=1;
}
}
return -1;
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
scanf("%s",a[i]+1);
for(int j=1;j<=m;j++)
{
if(a[i][j]=='r')
{
stx=i;
sty=j;
}
else if(a[i][j]=='a')
{
edx=i;
edy=j;
}
}
}
int ans=bfs();
if(ans==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: