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
思路:因为有耗时不同的差别,所以直接用BFS队列实现出来的结果不是最优的,所以呢,我们要控制一个时间最优的问题,所以我们采用时间优先队列来解决这个问题。。
AC代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct zuobiao
{
int x,y,output;
friend bool operator <(zuobiao a,zuobiao b)
{
return a.output>b.output;
}
}now,nex;
int n,m;
char a[1000][1000];
int vis[1000][1000];
int fx[4]={1,-1,0,0};
int fy[4]={0,0,1,-1};
void bfs(int x,int y)
{
priority_queue< zuobiao >s;
memset(vis,0,sizeof(vis));
now.x=x;
now.y=y;
now.output=0;
vis[now.x][now.y]=1;
s.push(now);
while(!s.empty())
{
now=s.top();
if(a[now.x][now.y]=='r')
{
printf("%d\n",now.output);
return ;
}
s.pop();
for(int i=0;i<4;i++)
{
nex.x=now.x+fx[i];
nex.y=now.y+fy[i];
nex.output=now.output+1;
if(nex.x>=0&&nex.x<n&nex.y>=0&nex.y<m&&a[nex.x][nex.y]!='#'&&vis[nex.x][nex.y]==0)
{
vis[nex.x][nex.y]=1;
if(a[nex.x][nex.y]=='x')
{
nex.output++;
s.push(nex);
}
else s.push(nex);
}
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int sx,sy;
for(int i=0;i<n;i++)
{
scanf("%s",&a[i]);
for(int j=0;j<n;j++)
{
if(a[i][j]=='a')
{
sx=i;sy=j;
}
}
}
bfs(sx,sy);
}
}
本文介绍了一个救援任务问题,其中需要计算从起始位置到达目标位置所需的最短时间,地图上包含障碍物、守卫等元素。文章详细解释了使用优先级队列的BFS算法来求解这一问题的方法。
1781

被折叠的 条评论
为什么被折叠?



