概述
Rescue
Total Submission(s): 32615 Accepted Submission(s): 11404
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
题意概括:
有一个天使被关在一个迷宫里,它的朋友要去救他。在迷宫里有墙、路和守卫。没走一步需要花费一单位的时间,杀死一个守卫需要一个单位的时间,也就是当走到有守卫的那一格时需要花费两个单位的时间。输出最短需要多长时间才能到达天使的位置,如果无法到达输出那一句话。
解题分析:
这题的坑就在于如果用广搜那么你最先到达终点位置的时间不一定就是最短的,所以你就需要把图全都跑一边,那么就会超时,用深搜也一样。因为这道题在碰到守卫时所需要的时间比正常路径多一个单位的时间,所以只需再到达守卫的位置时,将其出队,然后将其步数加一后的数据入队,这样就时它与正常路径一样了。
AC代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define N 205
struct node{
int x, y, s;
};
int n, m;
int book[N][N], Next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
char e[N][N];
int bfs(node h, node t)
{
memset(book, 0, sizeof(book));
int tx, ty, i;
node head, tail;
queue<node> q;
q.push(h);
book[h.x][h.y] = 1;
while(!q.empty())
{
head = q.front();
q.pop();
if(e[head.x][head.y] == 'x')//当遇到守卫时将其延迟一步
{
e[head.x][head.y] = '.';
head.s ++;
q.push(head);
continue;
}
for(i = 0; i < 4; i++)
{
tx = head.x + Next[i][0];
ty = head.y + Next[i][1];
if(tx < 0 || ty < 0 || tx >= n || ty >= m || e[tx][ty] == '#')
continue;
if(!book[tx][ty])
{
tail.x = tx;
tail.y = ty;
tail.s = head.s + 1;
book[tx][ty] = 1;
q.push(tail);
}
if(tx == t.x && ty == t.y)
return tail.s;
}
}
return -1;
}
int main()
{
int i, j, flag, k;
node h, t;
while(~scanf("%d%d", &n, &m))
{
for(i = flag = 0; i < n; i++)
{
scanf("%s", e[i]);
for(j = 0; j < m && flag != 2; j++)
{
if(e[i][j] == 'r')
{
h.x = i;
h.y = j;
h.s = 0;
}
else if(e[i][j] == 'a')
t.x = i, t.y = j;
}
}
k = bfs(h, t);
if(k != -1)
printf("%dn", k);
else
printf("Poor ANGEL has to stay in the prison all his life.n");
}
return 0;
}
最后
以上就是高高小馒头为你收集整理的HDU 1242 Rescue【BFS+优先队列】的全部内容,希望文章能够帮你解决HDU 1242 Rescue【BFS+优先队列】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复