题目中有一个很坑人的陷阱
#friends#
所以说要是从起点开始进行搜索那么起点是很多个的
所以我们可以从终点来开始进行搜索,这是整个题的核心
其他的没什么可说的了,简而言之,就是BFS的水题
下面附上AC代码
#include"iostream"
#include"cstdio"
#include"cstdlib"
#include"cstring"
using namespace std;
struct node
{
int x;
int y;
int len;
};
typedef struct node p;
p queue[50000];
int head;
int tail;
char map[205][205];
int book[205][205];
int n,m;
int bx,by;
int ex,ey;
int nextk[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int main()
{
int step=0;
int dx,dy;
int flag=0;
while(scanf("%d%d",&n,&m)==2)
{
step=0;
memset(book,0,sizeof(book));
memset(map,0,sizeof(map));
head=tail=1;
flag=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='a')
{
ex=i;
ey=j;
}
if(map[i][j]=='r')
{
bx=i;
by=j;
}
}
}
book[ex][ey]=1;
queue[1].x=ex;
queue[1].y=ey;
queue[1].len=0;
tail++;
while(head<tail)
{
for(int i=0;i<=3;i++)
{
dx=queue[head].x+nextk[i][0];
dy=queue[head].y+nextk[i][1];
if(map[dx][dy]=='r')
{
step=queue[head].len+1;
head=tail;
flag=1;
break;
}
if(dx<1||dx>n||dy<1||dy>m||map[dx][dy]=='#')
{
continue;
}
else
{
if(map[dx][dy]=='x'&&book[dx][dy]==0)
{
book[dx][dy]=1;
queue[tail].x=dx;
queue[tail].y=dy;
queue[tail].len=queue[head].len+2;
tail++;
}
if(map[dx][dy]=='.'&&book[dx][dy]==0)
{
book[dx][dy]=1;
queue[tail].x=dx;
queue[tail].y=dy;
queue[tail].len=queue[head].len+1;
tail++;
}
}
}
head++;
}
if(flag==1)
{
cout<<step<<endl;
}
else
{
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
}
return 0;
}