1.题目编号
1012
2.简单题意
天使(a)被困于迷宫,它的朋友(r)去救她,在迷宫中会有守卫(x)。r每走一步耗费一个单位的时间,如果路途遇上x,杀死x则需要一个单位的时间,求r找到a的最短时间。如果找不到就输出"Poor
ANGEL has to stay in the prison all his life."
3.思路
老师讲课讲过,此题是一个迷宫问题,求解最短路径。使用广度优先搜索可解,但是要注意细节,就是搜索的顺序带来的问题
4.感想
这是迷宫问题的第一道,感觉还是很难,要看看老师讲的例题,总结一下
5.代码
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x,y,step;
friend bool operator<(node n1,node n2)
{
return n2.step<n1.step;
}
};
int n,m,vis[205][205];
char map[205][205];
int x1,x2,y1,y2;
int to[4][2] = {1,0,-1,0,0,1,0,-1};
int check(int x,int y)
{
if(x<0 || y<0 || x>=n || y>=m || !vis[x][y] || map[x][y] == '#')
return 1;
return 0;
}
int bfs()
{
int i;
priority_queue<node> Q;
node a,next;
a.x = x1;
a.y = y1;
a.step = 0;
Q.push(a);
vis[x1][y1] = 0;
while(!Q.empty())
{
a = Q.top();
Q.pop();
if(a.x == x2 && a.y == y2)
return a.step;
for(i = 0; i<4; i++)
{
next = a;
next.x+=to[i][0];
next.y+=to[i][1];
if(check(next.x,next.y))//判断
continue;
next.step++;
if(map[next.x][next.y] == 'x')//卫兵处多花费了一秒
next.step++;
if(vis[next.x][next.y]>=next.step)//存入最小时间
{
vis[next.x][next.y] = next.step;
Q.push(next);
}
}
}
return 0;
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m))
{
for(i = 0; i<n; i++)
{
scanf("%s",map[i]);
for(j = 0; map[i][j]; j++)
{
if(map[i][j] == 'r')
{
x1 = i;
y1 = j;
}
else if(map[i][j] == 'a')
{
x2 = i;
y2 = j;
}
}
}
memset(vis,1,sizeof(vis));
int ans = 0;
ans = bfs();
if(ans)
printf("%d\n",ans);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}