解题思路:一直以为是一道简单的BFS,所以就用队列做的,结果WA了9次,和别人讨论之后才知道要用优先队列做。由于天使只有一个而朋友可能有很多,所以可以从天使开始BFS离他最近的朋友,如果可以到达朋友所在的位置就打印输出时间,否则输出Poor ANGEL has to stay in the prison all his life.
代码如下:
#include
#include
#include
#include
using namespace std;
const int maxn = 205;
const int maxm = 205;
typedef struct Node{
int x;
int y;
int t;
}node;
bool operator < (node a,node b)
{
return a.t > b.t;
}
char maze[maxn][maxm];
int dir[4][2] = {{0,1},{-1,0},{0,-1},{1,0}};
int ax,ay,rx,ry;
int m,n;
void bfs()
{
priority_queue que;
//queue que;
node temp,a;
a.x = ax;
a.y = ay;
a.t = 0;
maze[a.x][a.y] = '#';
que.push(a);
while(que.size()){
node p = que.top();
que.pop();
maze[p.x][p.y] = '#';
for(int i = 0;i < 4;i++){
int nx = p.x + dir[i][0];
int ny = p.y + dir[i][1];
if(0 <= nx && nx < n && 0 <= ny && ny < m && maze[nx][ny] != '#'){
if(maze[nx][ny] == 'r'){
printf("%d\n",p.t + 1);
return ;
}
else if(maze[nx][ny] == 'x'){
temp.t = p.t + 2;
}
else if(maze[nx][ny] == '.'){
temp.t = p.t + 1;
}
temp.x = nx;
temp.y = ny;
que.push(temp);
}
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main()
{
while(scanf("%d %d",&n,&m) != EOF){
for(int i = 0;i < n;i++){
scanf("%s",maze[i]);
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(maze[i][j] == 'a'){
ax = i;
ay = j;
break;
}
}
}
bfs();
}
return 0;
}
/*
在网上找了一份代码,运行下面的数据得到的结果不对,交到OJ上却AC了,奇怪
6 8
########
#.xxxx.#
#......#
#ax....r
rrrrrrrr
rrrrrrrr
*/