题目很短,好理解。存在多个目标r。单纯的普通队列+BFS是错的,即使你A了,换个遍历方向就WA了,见图
自己敲的代码比别人的好看多了
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define INF 0x7F7F7F7F
#define eps 10^(-6)
#define MEM(a) memset(a,0,sizeof(a));
#define MEM_BOOL(a) memset(a,false,sizeof(a));
#define FOR(i,n) for(int i=0;i<n;i++)
#define FIN freopen("in.txt","r",stdin);
#define FOUT freopen("out.txt","w",stdout);
#define NMAX 202
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int n,m;
char map[NMAX][NMAX];
bool visit[NMAX][NMAX];
struct node
{
int x,y;
int step;
bool operator < (const node &A)const
{
return step > A.step; //最小时间
}
};
bool isok(int x,int y)
{
if(map[x][y] != '#')
if(x >= 0 && x < n)
if(y >= 0 && y < m)
return 1;
return 0;
}
int bfs(node s)
{
node cur,tmp;
priority_queue<node>q;
while(!q.empty())
q.pop();
visit[s.x][s.y] = true;
q.push(s);
while(!q.empty())
{
tmp = q.top();
q.pop();
for(int i=0;i<4;i++)
{
cur.x = tmp.x + dir[i][0];
cur.y = tmp.y + dir[i][1];
if(!visit[cur.x][cur.y] && isok(cur.x,cur.y))
{
cur.step = tmp.step + 1;
if(map[cur.x][cur.y] == 'x')
cur.step ++;
if(map[cur.x][cur.y] == 'r')
return cur.step;
visit[cur.x][cur.y] = true;
q.push(cur);
}
}
}
return -1;
}
int main()
{
node s;
//FIN
int ans;
while(scanf("%d%d%*c",&n,&m)!=EOF)
{
MEM_BOOL(visit);
FOR(i,n)
{
FOR(j,m)
{
scanf("%c",&map[i][j]);
if(map[i][j] == 'a')
s.x = i, s.y = j,s.step = 0;
}
getchar();
}
ans = bfs(s);
if(ans != -1)
cout<<ans<<endl;
else
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
return 0;
}