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

HDOJ1242Rescue(BFS+优先队列)

2016-07-30 09:15 459 查看
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

题意:救人,a是被困的人,r是救援队,x是守卫,#是墙,‘.’是路。每走一步要1min,打败守卫要花1min,问能否救出人质,能输出最短时间,不能输出Poor ANGEL has to stay in the prison all his life.
思路:这是一道搜索题,一看要求最短时间就知道要用BFS比DFS好。首先找到救援队位置保存,从救援队位置开始搜索,入队列,分四个方向搜索,如果该方向符合题意如队列,如果搜索到‘x’,步数加一,搜索到人质位置返回该时间。搜索不到返回0.这里要用到优先队列找到最短路。
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#define MAXN 10000
using namespace std;
char map[1100][1100];
int vis[1100][1100];
int n,m;
int mi;
int sx,sy,ex,ey;
int dx[5]={1,-1,0,0};
int dy[5]={0,0,1,-1};
struct st{
int x;
int y;
int time;
bool friend operator<(st a,st b)
{
return a.time>b.time;
}
};
bool judge(st a)
{
if(a.x<0||a.x>=n||a.y<0||a.y>=m||map[a.x][a.y]=='#'||vis[a.x][a.y])
return false;
return true;
}
int bfs(int x,int y)
{
priority_queue<st>q;
while(!q.empty())
q.pop();
st a;
a.x=x;
a.y=y;
a.time=0;
vis[x][y]=1;
q.push(a);
while(!q.empty())
{
st b=q.top();
q.pop();
if(map[b.x][b.y]=='a')
return b.time;
for(int i=0;i<4;i++)
{
st end;
end.x=b.x+dx[i];
end.y=b.y+dy[i];
end.time=b.time;
if(judge(end))
{
if(map[end.x][end.y]=='x')
end.time++;
end.time++;
q.push(end);
vis[end.x][end.y]=1;
}
}
}
return 0;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(map,0,sizeof(map));
for(int i=0;i<n;i++)
{
scanf("%s",map[i]);
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(map[i][j]=='r')
{
memset(vis,0,sizeof(vis));
int ans=bfs(i,j);
if(ans<mi)
mi=ans;
}
}
memset(vis,0,sizeof(vis));
if(mi==0)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",mi);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: