Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.
Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.
You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)
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.
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."
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
13
题意:从a出发到r(r可能有多个),如果碰到x则需要两单位时间,遇到' . '需要1单位时间,求到达任意r需要的最短时间
思路:刚开始直接纯bfs,但是忘了考虑我们平时写的bfs队列queue,是把花费相同时间的点依次入队,但是本题中当我们碰到x时,时间会比' . '多1,如果还是用queue的话就可能会出现 ”1111211“这样的可能,因此应当使用优先队列priority_queue,优先队列的作用是保证按照数值的大小出列,会将以上序列按照“ 1111112 ”的顺序出列。
AC代码:
#include
#include
#include
#include
#include
#include
#include
#define maxn 205
using namespace std;
char maze[maxn][maxn];
int vis[maxn][maxn];
int d[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int n,m,stx,sty;
struct Node{
int x,y,step;
friend bool operator < (Node nows,Node nexts){
return nows.step > nexts.step; //此时较小的先出列,改成<则较大的先出列
}
}nows,nexts;
bool judge(int x,int y)
{
if(x<1||x>n||y<1||y>m) return false;
if(maze[x][y] == '#') return false;
if(vis[x][y]==1) return false;
return true;
}
int bfs()
{
priority_queue q; //优先队列
nows.x = stx;
nows.y = sty;
nows.step = 0;
q.push(nows);
while(!q.empty()){
nows = q.top(); //优先队列用q.top()
q.pop();
if(maze[nows.x][nows.y]=='r'){
return nows.step;
}
for(int i=0;i<4;++i){
nexts.x = nows.x+d[i][0];
nexts.y = nows.y+d[i][1];
if(judge(nexts.x,nexts.y)){
vis[nexts.x][nexts.y] = 1;
if(maze[nexts.x][nexts.y]=='x'){
nexts.step = nows.step+2;
}
else{
nexts.step = nows.step+1;
}
q.push(nexts);
}
}
}
return -1;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF){
getchar();
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
scanf("%c",&maze[i][j]);
if(maze[i][j]=='a'){
stx = i;
sty = j;
}
}
getchar();
}
vis[stx][sty] = 1;
int ans = bfs();
if(ans!=-1) printf("%d\n",ans);
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}