Description
Angel was caught by the moligpy! He was put into prison by Moligpy. The prison is described as a n * M (n, M <=) matrix. There is WALLs, ROADs, and guards in the prison.
Angel ' s friends want to save Angel. Their task Is:approach Angel. We assume that "approach Angel" are to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or his?) 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 had 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-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 the 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 have to stay in the prison all he life."
Sample Input
7 8
.#####.. a#. R ... #x ...
.. #.. #.#
...##..
.#......
........
Sample Output
13
Priority queue, encounter guard when two-step processing. The other one-step processing, each time from the queue to find the minimum number of steps to operate until the results are found.
#include <cstdio>#include <queue>#include <cstring>using namespace STD;intcnv[4][2]={{1,0},{0,1},{-1,0},{0,-1}};structrac{intx,y,cnt;BOOL operator< (ConstRAC & P)Const{returnCNT > p.cnt; }};Charmp[205][205];intvisit[205][205];intSx,sy,tx,ty;intN,m;intMain () { while(scanf("%d%d", &m,&n) = =2) {intI,j; GetChar (); for(i=0; i<m;i++) { for(j=0; j<n;j++) {scanf("%c", &mp[i][j]);if(mp[i][j]==' R ') {sx=i; Sy=j; }Else if(mp[i][j]==' A ') {tx=i; Ty=j; }} getchar (); }memset(Visit,0,sizeof(visit)); priority_queue<rac>q; Rac s; S.X=SX; S.y=sy; S.cnt=0; visit[sx][sy]=1; Q.push (s);BOOLok=false; while(!ok&&q.empty () = =false) {Rac t=q.top (); Q.pop (); for(i=0;i<4; i++) {intx=t.x+cnv[i][0];inty=t.y+cnv[i][1];if(x>=0&&x<m&&y>=0&&y<n&&visit[x][y]==0&&mp[x][y]!=' # ') {if(mp[x][y]=='. ') {visit[x][y]=1; RAC T2; T2.x=x; T2.y=y; t2.cnt=t.cnt+1; Q.push (T2); }Else if(mp[x][y]==' x ') {visit[x][y]=1; RAC T2; T2.x=x; T2.y=y; t2.cnt=t.cnt+2; Q.push (T2); }Else if(mp[x][y]==' A ') {ok=true;printf("%d\n", t.cnt+1); Break; } } } }if(!ok)printf("Poor ANGEL have to stay in the prison all his life.\n");//cannot reach}return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Rescue zoj1649 Priority Queue