概述
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
题目大意 : 在一张图中, ‘a’表示天使, ‘r’表示天使的朋友,朋友可能有多个, ‘#’表示障碍, 不可经过, ‘x’表示警卫, 正常在地图中走一步需要话一个单位时间, 打败警卫需要多花费一个单位时间 。
思路 : 不难看出这其实就是一张带权图, 所以我们在输入的时候可以顺便把每张图都附上权值, 障碍不可经过, 可以设置也可以不设,警卫权值设为2, 其余权值设为1,然后bfs + 优先队列搜就完事儿了,原理和迪杰特斯拉一样, 不断地找最近的路并更新最短路。
AC代码 :
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 2e2 + 5;
const int INF = 0x3f3f3f3f;
struct node
{
int x, y, w;
bool operator < (const node &oth) const
{
return w > oth.w;
}
};
char p[maxn][maxn];
int val[maxn][maxn], n, m, sx, sy, sum;
bool vis[maxn][maxn], flag;
void bfs() {
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
memset(vis, 0, sizeof(vis));
flag = 0;
priority_queue <node> q;
q.push({sx, sy, 0});
vis[sx][sy] = 1;
while (!q.empty()) {
node now = q.top();
q.pop();
if (p[now.x][now.y] == 'r') {
sum = now.w;
flag = 1;
return;
}
for (int i = 0; i < 4; i++) {
int xx = now.x + dir[i][0];
int yy = now.y + dir[i][1];
if (xx >= 0 && yy >= 0 && xx < n && yy < m && !vis[xx][yy] && p[xx][yy] != '#') {
vis[xx][yy] = 1;
q.push({xx, yy, now.w + val[xx][yy]});
}
}
}
}
int main()
{
while (cin >> n >> m) {
for (int i = 0; i < n; i++) {
cin >> p[i];
for (int j = 0; j < m; j++) {
if (p[i][j] == 'a') sx = i, sy = j;
else if (p[i][j] == '#') val[i][j] = INF;
else if (p[i][j] == 'x') val[i][j] = 2;
else val[i][j] = 1;
}
}
bfs();
if (flag) cout << sum << endl;
else cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}
return 0;
}
最后
以上就是孝顺嚓茶为你收集整理的#HDU 1242 Rescue (BFS + 优先队列)的全部内容,希望文章能够帮你解决#HDU 1242 Rescue (BFS + 优先队列)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复