标签:
7 8 #.#####. #.a#..r. #..#x... ..#..#.# #...##.. .#...... ........
13
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
char MAP[202][202];
bool visit[202][202];
struct node{
int x,y;
int flag;
};
int u[4]={1,0,-1,0};
int v[4]={0,1,0,-1};
int cmp(node a,node b){
return a.flag<b.flag;
}
int BFS(int i,int j){
queue<node> Q; //Q要在数组内定义,否则要记得每次用之前将队列清空,因为上次的队列可能会由于没有完全出队而保留上次的数据,其中我在这就出了错!
node t;
t.x=i; t.y=j;
t.flag=0;
Q.push(t);
visit[i][j]=1;
while(!Q.empty()){
t=Q.front();
int tx,ty;
tx=t.x;ty=t.y;
if(MAP[tx][ty]=='r'){
return t.flag;
}
Q.pop();
node temp[4];
int p=0,k;
for(k=0;k<4;++k){
if(MAP[tx+u[k]][ty+v[k]]!='#'&&!visit[tx+u[k]][ty+v[k]]){
if(MAP[tx+u[k]][ty+v[k]]=='x'){
temp[p].x=tx+u[k];
temp[p].y=ty+v[k];
visit[temp[p].x][temp[p].y]=1;
temp[p].flag=t.flag+2;
++p;
}
else{
temp[p].x=tx+u[k];
temp[p].y=ty+v[k];
visit[temp[p].x][temp[p].y]=1;
temp[p].flag=t.flag+1;
++p;
}
// Q.push(temp); //此处不能 直接入队,因为同等级的 r要比 x耗时短,所以先将 t上下左右的四个点存放到数组中
}
}
sort(temp,temp+p,cmp); //经过排列后再依次入队
for(k=0;k<p;++k){
Q.push(temp[k]);
}
}
return -1;
}
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)){
int i,j;
for(i=0;i<=n+1;++i){
for(j=0;j<=m+1;++j){
MAP[i][j]='#';
}
}
int ax,ay;
for(i=1;i<=n;++i){
getchar();
for(j=1;j<=m;++j){
scanf("%c",&MAP[i][j]);
if(MAP[i][j]=='a') ax=i,ay=j;
}
}
memset(visit,0,sizeof(visit));
int res=BFS(ax,ay);
if(res==-1) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",res);
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qq_18062811/article/details/47422413