搜索专题: HDU1242 Rescue
RescueTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31648 Accepted Submission(s): 11083
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
Sample Output
Author
CHEN, Xue
Source
Recommend
这次被困住的是天使,不是公主了,但是该救还是得救,还是BFS;
代码如下:
Problem :
1242 ( Rescue ) Judge Status : Accepted
RunId : 21282960 Language : G++ Author : hnustwanghe Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta #include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; const int N = 200 + 5; char mat[N][N]; bool visit[N][N]; typedef struct node{ int x,y,val; bool operator < (const node x)const { return val > x.val; } }Node; int goalx,goaly,startx,starty,n,m; const int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; int BFS(){ priority_queue<Node> Q; memset(visit,0,sizeof(visit)); Node t,s; int newx,newy; visit[startx][starty] = true; Q.push((Node){startx,starty,0}); while(!Q.empty()){ t = Q.top();Q.pop(); if(t.x == goalx && t.y == goaly ) return t.val; for(int d=0;d<4;d++){ newx = t.x + dir[d][0]; newy = t.y + dir[d][1]; if(!visit[newx][newy] && newx>=0 && newx<n && newy>=0 && newy < m && mat[newx][newy]!='#'){ int val = (mat[newx][newy]=='x')?2:1; s.x = newx,s.y= newy,s.val = t.val + val; visit[newx][newy] = true; Q.push(s); } } } return -1; } int main(){ while(scanf("%d %d",&n,&m)==2){ for(int i=0;i<n;i++){ scanf("%s",mat[i]); for(int j=0;j<m;j++) if(mat[i][j]=='r') startx = i,starty = j; else if(mat[i][j]=='a') goalx = i,goaly = j; } int ans = BFS(); if(ans < 0) printf("Poor ANGEL has to stay in the prison all his life.\n"); else printf("%d\n",ans); } } |