链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
angel被困在迷宫里,他的朋友们去救。n*m的迷宫,'.'代表路,'#'代表墙,'x'代表守卫,'r'代表朋友,'a'代表ANGEL。求最少时间。由于该题目仅含有一个a点,但是可以含有多个r点,所以从a点开始搜,这点很容易想到。可是写了很久一直Wa,Wa的莫名其妙的感觉,然后看了些题解,说是优先队列,在此之前,应该是没有做过优先队列,这是我的第一道,然后连重载都不会的我去看了优先队列这部分。因为当步数相同时时间不一定是最小的,所以要进行处理,这时候优先队列的优势就出来了,也确实,很容易就Ac了,不过好像好多人没用优先队列也过了。
代码:
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
char map[205][205];
int n,m;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int si,sj;
struct point
{
int x,y,time;
friend bool operator < (point a, point b)
{
return a.time>b.time; //时间少的先出队
}
} start;
int BFS(int a,int b)
{
start.x=a;
start.y=b;
start.time=0;
priority_queue<point> q;
point cur,next;
int i;
q.push(start);
while(!q.empty())
{
cur=q.top(); //取出队首元素
q.pop();
for(i=0;i<4;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
next.time=cur.time+1;
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m)
if(map[next.x][next.y]!='#')
{
if(map[next.x][next.y]=='x')
next.time++;
if(map[next.x][next.y]=='r')
return next.time;
map[next.x][next.y]='#';
q.push(next);
}
}
}
return -1;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='a')
{
si=i;
sj=j;
}
}
getchar();
}
int count=BFS(si,sj);
if(count>=0)
printf("%d\n",count);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
/*
5 4
####
#xa.
#x#.
#x#.
#r..
*/