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
Solution
题目大意:安琪儿被魔王抓走,她的朋友们想救她,’r’为起点,’a’为终点,’.’为通道,’#’为墙,’x’为守卫,每走一步需要一单位时间,碰到守卫需要多花一单位时间。求救出安琪儿最短需要多少时间。 解题思路:没有守卫的话,这道题就是普通的BFS,加了守卫,所以需要用优先队列,每次取出步数小的点。Code
#include#include #include #include using namespace std;const int INF = 10000000;#define maxn 210struct node{ int x, y, step; bool operator<(const node &b)const { return step>b.step; }};int dir[4][2] = { { -1,0 },{ 0,-1 },{ 1,0 },{ 0,1 } }; //方向int n, m, d[maxn][maxn]; //d为到各个位置最短距离数组char s[maxn][maxn];int bfs(node a){ priority_queue que; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = INF; que.push(a); d[a.x][a.y] = 0; while (!que.empty()) { node now = que.top(); que.pop(); int x = now.x, y = now.y, step = now.step; if (s[x][y] == 'a') return step; for (int i = 0; i < 4; i++) { int xx = x + dir[i][0], yy = y + dir[i][1]; if (!(xx<1 || xx>n || yy>m || yy<1 || s[xx][yy] == '#')) { node next; next.x = xx; next.y = yy; next.step = step + 1; if (s[xx][yy] == 'x') next.step++; if (d[xx][yy]>next.step) { d[xx][yy] = next.step; que.push(next); } } } } return INF;}int main(int argc, char const *argv[]){ while (~scanf_s("%d%d", &n, &m)) { node a; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> s[i][j]; if (s[i][j] == 'r') { a.x = i; a.y = j; a.step = 0; } } int ans = bfs(a); if (ans != INF) printf("%d\n", ans); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0;}