Rescue
借鉴了大神的思路
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.”
BFS加优先队列
Sample Input
7 8
#.#####.
#.a#..r.
#..#x…
..#..#.#
#…##..
.#……
……..
Sample Output
13
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int N,M;
struct node
{
int x,y;
int step;
};
bool operator<( node a, node b){
return a.step>b.step;
}
char map[202][202];
int x1,y1,maxn;
int vis[202][202],x2,y2,time;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int check(int a,int b)
{
if(a<0||b<0||a>=N||b>=M||map[a][b]=='#'){
return 0;
}
if(vis[a][b]==1){
return 0;
}
return 1;
}
int dfs()
{
int i,j;
priority_queue<node> q;
node a,next;
a.x=x1;
a.y=y1;
// cout<<x1<<' '<<y1<<endl;
a.step=0;
vis[x1][y1]=1;
q.push(a);
while(!q.empty()){
a=q.top();
q.pop();
// cout<<a.x<<' '<<a.y<<endl;
if(a.x==x2&&a.y==y2){
return a.step;
}
for(i=0;i<4;i++){
next.x=a.x+dir[i][0];
next.y=a.y+dir[i][1];
if(check(next.x,next.y)){
next.step=a.step+1;
vis[next.x][next.y]=1;
if(map[next.x][next.y]=='x'){
// cout<<next.x<<' '<<next.y<<endl;
next.step=a.step+2;
}
q.push(next);
}
}
}
return 0;
}
int main()
{
while(scanf("%d%d",&N,&M)!=EOF){
memset(vis,0,sizeof(vis));//!!!!!!!
for(int i=0;i<N;i++){
scanf("%s",map[i]);
for(int j=0;map[i][j]!='\0';j++){
if(map[i][j]=='r'){
x1=i;y1=j;
}
if(map[i][j]=='a'){
x2=i;y2=j;
}
}
}
int ans=0;
ans=dfs();
if(ans)
{
printf("%d\n",ans);
}
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}