Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21644 Accepted Submission(s): 7721
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.)
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.
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
#define MAX 220
char map[MAX][MAX];
int d[4][2]{0,1,0,-1,1,0,-1,0};
int vis[MAX][MAX],N,M,sx,sy,ans;
struct node{
int x,y,step;
};
bool operator <(const node &a,const node &b){
if(a.step==b.step)
return a.x<b.x;
return b.step<a.step;
}
node now;
node then;
bool juge(int a,int b){
if(a>N||a<1||b>M||b<1||vis[a][b]||map[a][b]=='#')
return false;
return true;
}
void bfs(){
now.x=sx;
now.y=sy;
now.step=0;
memset(vis,0,sizeof(vis));
priority_queue<node>q;
q.push(now);
vis[sx][sy]=1;
while(!q.empty()){
now=q.top();
q.pop();
for(int v=0;v<4;v++){
then.x=now.x+d[v][0];
then.y=now.y+d[v][1];
if(juge(then.x,then.y)){
if(map[then.x][then.y]=='x')
then.step=now.step+2;
else
then.step=now.step+1;
if(map[then.x][then.y]=='r'){
ans=then.step;
return;
}
vis[then.x][then.y]=1;
q.push(then);
}
}
}
}
int main(){
while(scanf("%d%d",&N,&M)!=EOF){
for(int n=1;n<=N;n++){
getchar();
for(int m=1;m<=M;m++){
scanf("%c",&map[n][m]);
if(map[n][m]=='a'){
sx=n;sy=m;//記錄下a的座標爲起點
}
}
}
ans=INF;
bfs();
if(ans!=INF)//ans值不變表示沒有可解救的通路
printf("%d\n",ans);
else
puts("Poor ANGEL has to stay in the prison all his life.");
}
return 0;
}