Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 16314 Accepted Submission(s): 5926
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
Author
CHEN, Xue
Source
#include <stdio.h> #include <string.h> #include <queue> #define maxn 202 using std::priority_queue; int n, m, ans; const int mov[][2] = {0, 1, 0, -1, -1, 0, 1, 0}; char map[maxn][maxn]; struct Node{ int x, y, time; friend bool operator<(Node a, Node b){ return a.time > b.time; } }; bool check(int x, int y){ return x >= 0 && x < n && y >= 0 && y < m && map[x][y] != '#'; } bool BFS(int x, int y) { Node now, tmp; now.x = x; now.y = y; map[x][y] = '#'; now.time = 0; priority_queue<Node> Q; Q.push(now); while(!Q.empty()){ now = Q.top(); Q.pop(); for(int i = 0; i < 4; ++i){ tmp = now; tmp.x += mov[i][0]; tmp.y += mov[i][1]; if(check(tmp.x, tmp.y)){ ++tmp.time; if(map[tmp.x][tmp.y] == 'x') ++tmp.time; else if(map[tmp.x][tmp.y] == 'r'){ ans = tmp.time; return true; } map[tmp.x][tmp.y] = '#'; Q.push(tmp); } } } return false; } int main() { int i, j, x, y; while(scanf("%d%d", &n, &m) == 2){ for(i = 0; i < n; ++i){ getchar(); for(j = 0; j < m; ++j){ map[i][j] = getchar(); if(map[i][j] == 'a'){ x = i; y = j; } } } if(BFS(x, y)) printf("%d\n", ans); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; }
HDU1242 Rescue 【BFS】,布布扣,bubuko.com