#include<iostream>
#include<stdio.h>
#include<string>
#include<queue>
using namespace std;
#define MAX 210
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};char map[MAX][MAX];
int mask[MAX][MAX];
class Point
{
public:
int x;
int y;
int c;
};
Point s,e;int N,M;//N是行,M是列
int over(Point p)
{
if(p.x<0||p.y<0) return 1;
if(p.x>=M||p.y>=N) return 1;
return 0;
}
void bfs()
{
s.c=0;mask[s.x][s.y]=0;
queue<Point>q;
q.push(s);
Point p,cs;int i;
while(!q.empty())
{
p=q.front();q.pop();
for(i=0;i<4;i++)
{
cs.x=p.x+dir[i][0];cs.y=p.y+dir[i][1];cs.c=p.c+1;
if(over(cs)||map[cs.x][cs.y]=='#')
continue;
if(map[cs.x][cs.y]=='x')
cs.c++;
if(mask[cs.x][cs.y]==-1||cs.c<mask[cs.x][cs.y])
{
mask[cs.x][cs.y]=cs.c;
q.push(cs);
}
}
}
}
void init()
{
int i,j;
for(i=0;i<MAX;i++)
{
for(j=0;j<MAX;j++)
{
map[i][j]='0';
mask[i][j]=-1;//标记没有访问
}
}
}
int main()
{
//freopen("input.txt","r",stdin);
while(scanf("%d%d",&N,&M)!=EOF)
{
//初始化
init();
//输入
getchar();char temp[MAX];
int i,j;
for(i=0;i<N;i++)
{
gets(temp);
for(j=0;j<M;j++)
{
map[j][i]=temp[j];
//标记开始点
if(map[j][i]=='r')
{
map[j][i]='.';
s.x=j;s.y=i;
}
//标记结束点
if(map[j][i]=='a')
{
map[j][i]='.';
e.x=j;e.y=i;
}
}
}
//开始处理
bfs();
if(mask[e.x][e.y] == -1)
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
else
cout<<mask[e.x][e.y]<<endl;
}
}
/*
1 freopen("input.txt","r",stdin);
会导致wa,以后要注意
2 这个思路很清晰,以后就照这个写
3 queue只存在于bfs()当中,
4 bfs()中不能有return。因为如果说中文是全世界最美丽的语言,但是我现在只学啦中文,不能这样说
要把全部的语言都试一次才可以这样说。
*/
hdoj 1242(这样写bfs才清晰,而且容易debug)
最新推荐文章于 2019-06-09 18:06:10 发布