我是靠谱客的博主 妩媚火车,最近开发中收集的这篇文章主要介绍zoj 1649 Rescue【BFS+优先队列】,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Rescue

Time Limit: 2 Seconds       Memory Limit: 65536 KB

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是警察,a走到“.”的耗时为1,a要想干掉"x"耗时也是1,因为走到这个格子耗时也是 1,所以加在一起就是2,。问最小救到r的步数,如果不能救到,输出Poor ANGEL has to stay in the prison all his life.


思路:因为有耗时不同的差别,所以直接用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+优先队列】所遇到的程序开发问题。

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

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

评论列表共有 0 条评论

立即
投稿
返回
顶部