HDU1242 Rescue

Time Limit: 1000MS   Memory Limit: 32768KB   64bit IO Format: %I64d & %I64u

Description

Angel was caught by the MOLIGPY! He was put in * by Moligpy. The * is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the *.

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 * all his life." 
 

Sample Input

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
 

Sample Output

13
 

Source

ZOJ Monthly, October 2003

由于引入了"杀死守卫"这一额外耗费时间的情况,所以第一次BFS到终点时的解不一定最优,应该不断更新经过节点的值,直到不能更新,跑完整个BFS队列,才能得到最优解

 /*by SilverN*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cmath>
using namespace std;
const int INF=;
const int mxn=;
struct node{
int x,y;
int w;//用时
};
queue<node>q;
int mx[]={,,,-,},
my[]={,,,,-};
int ax,ay;
char mp[mxn][mxn];
int ans[mxn][mxn];
int n,m; void BFS(node s){
q.push(s);
int i;
node hd;
while(!q.empty()){
hd=q.front();
q.pop();
for(i=;i<=;i++){
int x=hd.x+mx[i];
int y=hd.y+my[i];
if(x> && x<=n && y> && y<=m && mp[x][y]!='#'){
node v;
v.x=x; v.y=y; v.w=hd.w+;
if(mp[x][y]=='x') v.w++;//杀死守卫要多花时间
if(v.w<ans[x][y]){
ans[x][y]=v.w;
q.push(v);
}
}
}
}
return;
}
int main(){
int i,j;
while(scanf("%d%d",&n,&m)!=EOF){
memset(mp,' ',sizeof(mp));
int sx,sy;
node ST;
for(i=;i<=n;i++){
scanf("%s",mp[i]+);
for(j=;j<=m;j++){
ans[i][j]=INF;
if(mp[i][j]=='a'){ax=i;ay=j;}
else if(mp[i][j]=='r'){sx=i;sy=j;}
else if(mp[i][j]!='.' && mp[i][j]!='x')mp[i][j]='#';
//从讨论区看到数据里可能有其他符号,也应算作#
}
}
ST.x=sx;ST.y=sy;ST.w=;
ans[sx][sy]=;
BFS(ST);
if(ans[ax][ay]!=INF)printf("%d\n",ans[ax][ay]);//有解
else printf("Poor ANGEL has to stay in the * all his life.\n");//无解
}
return ;
}
上一篇:.Net程序员学习Linux(一)


下一篇:IOS平台汉字转拼音方案