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
解题报告:本题比较经典的地方的是杀死士兵需要增加一个时间,所以不能简单的用哪个先到达终点来进行判断。
所以这里开了一个mintiime数组来记录走到每一点所花费的最少的时间来判断走到每一点所需要的最少的时间
这样子既不会使走过的路被重复的走,又能保证最终是最少的步数;
#include<cstdio> #include<cstring> #include<queue> #define maxn 200 + 5 #define INF 0x7ffffff using namespace std; struct node { int x, y; int time; }; int dir[4][2] = {0,1,0,-1,1,0,-1,0}; int mintime[maxn][maxn]; char mp[maxn][maxn]; int ex, ey, sx, sy, n, m; queue < node >Q; int bfs( node start) { int i; node pre; Q.push(start); while(!Q.empty( ) ) { pre = Q.front( ); Q.pop( ); for(i = 0; i < 4;i++ ) { int x = pre.x + dir[i][0]; int y = pre.y + dir[i][1]; if(x<n && x>=0 && y<m && y>=0 && mp[x][y] != '#') { node t; t.x = x; t.y = y; t.time = pre.time + 1; if(mp[x][y]=='x') t.time ++; if(t.time < mintime[x][y]) { mintime[x][y] = t.time; Q.push( t ); } } } } return mintime[ex][ey]; } int main() { while( scanf( "%d%d",&n, &m) != EOF ) { node start; memset( mp, 0, sizeof( mp ) ); for(int i=0;i<n;i++) { scanf("%s",mp[i]); for( int j = 1; j<m; j++) { mintime[i][j] = INF; if(mp[i][j] == 'r') { sx = i; sy = j;} else if( mp[i][j] == 'a') { ex = i; ey = j;} } } start.x = sx; start.y = sy; start.time = 0; mintime[sx][sy] = 0; int ans = bfs( start ); if( ans < INF ) printf("%d\n",ans); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; }