整个题目没有太大的难度,就是搜索计时,求最小的时间的问题,但是在做的的时候用到了优先队列,在这种优先队列,优先队列对于像这种广度搜索还是非常不错的。在以后做题的时候要多多考虑这些方法。
#include <cstdio>
#include <string.h>
#include <iostream>
#include <queue>
#include<functional>
#include <cstdlib>
using namespace std;
struct node
{
friend bool operator <(node n1,node n2)
{
return n1.time>n2.time;
}
int x;
int y;
int time;
};
int v[202][202];
char map[202][202];
int m,n;
int x,y;
int BFS(int a,int b)
{
int i,j,flag=1;
int k=0;
node st,en;
st.x=a;
st.y=b;
st.time=0;
priority_queue<node>q;//定义一个优先队列
q.push(st);
while(!q.empty())//开始进入搜索
{
st=q.top();
q.pop();
i=st.x;
j=st.y;
if(i==x&&j==y)
return st.time+1;
//下面分了四中情况,这样列举几种情况还是比较复杂繁琐的,看了一些大牛的博客 ,貌似都比我的好,用数组的比较多 下次我可以试一试
if(map[i+1][j]!='#'&&v[i+1][j]==0&&i+1<n&&i!=-1)
{
if(map[i+1][j]=='x')
{
en.time=st.time+2;
}
else
en.time=st.time+1;
en.x=i+1;
en.y=j;
q.push(en);
v[i+1][j]=1;
}
if(map[i][j+1]!='#'&&v[i][j+1]==0&&j+1<m&&i!=-1)
{
if(map[i][j+1]=='x')
{
en.time=st.time+2;
}
else
en.time=st.time+1;
en.x=i;
en.y=j+1;
q.push(en);
v[i][j+1]=1;
}
if(map[i][j-1]!='#'&&v[i][j-1]==0&&j-1>=0&&i!=-1)
{
if(map[i][j-1]=='x')
{
en.time=st.time+2;
}
else
en.time=st.time+1;
en.x=i;
en.y=j-1;
q.push(en);
v[i][j-1]=1;
}
if(map[i-1][j]!='#'&&v[i-1][j]==0&&i-1>=0&&i!=-1)
{
if(map[i-1][j]=='x')
{
en.time=st.time+2;
}
else
en.time=st.time+1;
en.x=i-1;
en.y=j;
q.push(en);
}
}
return -1;
}
int main()
{
int a,b;
int i,j;
//freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(v,0,sizeof(v));
for(i=0;i<n;i++)
{
scanf("%s",&map[i]);
for(j=0;j<m;j++)
{
if(map[i][j]=='r')
{
a=i;b=j;
}
if(map[i][j]=='a')
{
x=i;y=j;
}
}
}
int count= BFS(a,b);
if(count==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",count-1);
}
return 0;
}