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
不是以为有的格子要打败守卫,造成到某一个格子的时间不同,造成不是等距树,所以会掩盖某些较短的路
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int maxn=200+10;
const int inf=99999999;
int vis[maxn][maxn];
int mp[maxn][maxn];
int sx,sy,ex,ey;
int ans;
int n,m,flag;
int dis[4][2]={-1,0,0,1,1,0,0,-1};
struct node {
int x,y;
int step;
};
int check(int x,int y) {
if(x<1||y<1||x>n||y>m) return 1;
//if(vis[x][y]) return 1;
if(mp[x][y]==0) return 1;
return 0;
}
void bfs() {
node a,next;
a.x=sx;
a.y=sy;
a.step=0;
vis[sx][sy]=0;
queue<node> q;
q.push(a);
while(!q.empty()) {
a=q.front();
// cout<<a.x<<" "<<a.y<<endl;
q.pop();
if(a.x==ex&&a.y==ey) {
if(ans>a.step) {
flag=1;
ans=a.step;
}
}
for(int i=0;i<4;i++) {
next.x=a.x+dis[i][0];
next.y=a.y+dis[i][1];
if(check(next.x,next.y))
continue;
if(mp[next.x][next.y]==1) next.step=a.step+1;
if(mp[next.x][next.y]==2) next.step=a.step+2;//bfs并不是等距的,造成某些短路被提前走过
if(vis[next.x][next.y]>a.step) {
q.push(next);
vis[next.x][next.y]=a.step;
}
}
//cout<<a.x<<" "<<a.y<<endl;
}
}
int main() {
// freopen("input.txt","r",stdin);
while(scanf("%d%d\n",&n,&m)!=EOF) {
flag=0;
char ch[300];
ans=99999999999;
memset(mp,0,sizeof(mp));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) {
vis[i][j]=inf;
}
for(int i=1;i<=n;i++) {
scanf("%s",ch);
for(int j=0;j<m;j++) {
if(ch[j]=='.') mp[i][j+1]=1;
if(ch[j]=='x') mp[i][j+1]=2;
if(ch[j]=='r') {
mp[i][j+1]=1;
sx=i;
sy=j+1;
}
if(ch[j]=='a') {
mp[i][j+1]=1;
ex=i;
ey=j+1;
}
}
}
bfs();
if(flag) printf("%d\n",ans);
else printf("Poor ANGEL has to stay in the * all his life.\n");
}
return 0;
}