Problem Description
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.)
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
Author
CHEN, Xue
Source
ZOJ Monthly, October 2003
Recommend
Eddy
题意:给出一个地图,天使的朋友拯救天使,每走一步需要时间单位1,途中可能有怪兽,消灭需要时间单位1,。问你最少拯救天使的时间。
这题数据好像不怎么强。方法有很多,bfs,dfs 。一道简单搜索题。
我用优先队列和普通的队列都能过,时间都15ms。注意救不了还要输出一句话的,这里我wa了好几发,真的读题不仔细唉。
#include
#define rep(i,x,y) for(int i=(x);i<(y);i++)
#define IOS() ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
int const N=202;
int n,m;
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int startx,starty,endx,endy;//起点(startx,starty) 终点(endx,endy)
char s[N][N];
int vis[N][N];
void init()
{
memset(vis,0,sizeof(vis));
}
struct node
{
int x;
int y;
int time;
friend bool operator< (const node &a,const node &b)//时间小的先出
{
return a.time>b.time;
}
};
int judge(int x,int y)
{
if(x<0||y<0||x>=n||y>=m||vis[x][y]==1||s[x][y]=='#')return 1;
else return 0;
}
int bfs(int x,int y)
{
//生成节点
priority_queue<node>q;
node t,u;
t.time=0;
t.x=x;
t.y=y;
vis[t.x][t.y]=1;
q.push(t);
while(!q.empty())
{
t=q.top();
q.pop();
if(t.x==endx&&t.y==endy)return t.time;
for(int i=0;i<4;i++)
{
u.x=t.x+dir[i][0];
u.y=t.y+dir[i][1];
if(judge(u.x,u.y))continue;
if(s[u.x][u.y]=='x')
{
u.time=t.time+2;
}
else
{
u.time=t.time+1;
}
vis[u.x][u.y]=1;
q.push(u);
}
}
return -1;
}
int main()
{
IOS();
while(cin>>n>>m)
{
init();
rep(i,0,n)
{
rep(j,0,m)
{
cin>>s[i][j];
if(s[i][j]=='r')
{
startx=i;
starty=j;
}
if(s[i][j]=='a')
{
endx=i;
endy=j;
}
}
}
int ans=bfs(startx,starty);
if(ans==-1)printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",ans);
}
return 0;
}