Input
First line contains two integers stand for N and M.
Then N lines follows, every line has M characters. “.” stands for road, “a” stands for Angel, and “r” stands for each of Angel’s friend.
Process to the end of the file.
Output
For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing “Poor ANGEL has to stay in the prison all his life.”
Sample Input
7 8
#.#####.
#.a#…r.
#…#x…
…#…#.#
#…##…
.#…
…
Sample Output
13
对该题进行遍历,求出最短路径,用了btf算法,和优先队列可以求出最短路径,代码如下
#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y;
int step;
}; ///定义一个结构体存放坐标,步数
int N,M,prove,visit[210][210],sx,sy;
char mp[210][210];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,1,-1};
queue q;
int check(int x,int y)
{
if(x <0 || x >= N || y < 0 || y >= M)
return 0;
else
return 1;
} ///检查是否数据溢出
void BFS()
{
while(!q.empty())
q.pop();
node s,e;
memset(visit,0,sizeof(visit)); ///使visit数组内都为0
s.step=0;s.x=sx;s.y=sy;
q.push(s);
visit[s.x][s.y]=1; ///在visit 内走过的点标记为1,防止重复
while(!q.empty())
{
s=q.front();
q.pop();
if(mp[s.x][s.y] == ‘a’)
{
cout<<s.step<<endl;
prove=1;
} ///如果所在点为a 则输出步数
if(mp[s.x][s.y]‘x’)
{
mp[s.x][s.y]=’.’;
s.step+=1;
q.push(s);
continue;
} ///如果所在点为x则步数加1在换位通路
for(int i=0;i<4;i++)
{
e.x=s.x+dx[i];e.y=s.y+dy[i];
if(!check(e.x,e.y)||visit[e.x][e.y]||mp[e.x][e.y]’#’)
continue; ///如果该点数据溢出或走过或为墙则跳过该点
e.step=s.step+1;
q.push(e);
visit[e.x][e.y]=1;
}
}
}
int main()
{
while(cin>>N>>M)
{
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
{
cin>>mp[i][j];
if(mp[i][j]==‘r’)
{
sx=i;
sy=j;
} ///标记起始位置
}
prove=0;
BFS();
if(!prove)
cout<<“Poor ANGEL has to stay in the prison all his life.”<<endl;
}
return 0;
}