概述
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("%dn",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);
}
}
最后
以上就是妩媚火车为你收集整理的zoj 1649 Rescue【BFS+优先队列】的全部内容,希望文章能够帮你解决zoj 1649 Rescue【BFS+优先队列】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复