1039: Rescue
Time Limit: 1 Sec Memory Limit: 32 MB
Submit: 1320 Solved: 306
Description
Angel was caught by the MOLIGPY! He was put in * by Moligpy. The * is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the *. 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 * all his life."
Sample Input
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
用优先队列+bfs,写得蛮有逻辑性(哈哈):
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define MAX_N 205
using namespace std;
struct Node
{
int x,y,t;
bool operator<(const Node &a)const
{
return t>a.t;
}
}; Node start; char map[MAX_N][MAX_N]; int dir[][]={{,},{,-},{,},{-,}}; int n,m; int bfs()
{
priority_queue<Node> que;
Node cur,next;
int i,j;
map[start.x][start.y]='#';
que.push(start);
while(!que.empty())
{
cur=que.top();
que.pop();
for(i=;i<;i++)
{
next.x=cur.x+dir[i][];
next.y=cur.y+dir[i][];
next.t=cur.t+; if(next.x<||next.x>=n||next.y<||next.y>=m)
continue;
if(map[next.x][next.y]=='#')
continue;
if(map[next.x][next.y]=='r')
return next.t;
if(map[next.x][next.y]=='x')
{
next.t++;
map[next.x][next.y]='#';
que.push(next);
}
else if(map[next.x][next.y]=='.')
{
map[next.x][next.y]='#';
que.push(next);
}
}
}
return -;
} int main()
{
// freopen("a.txt","r",stdin);
int i,ans;
char *p;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=;i<n;i++)
{
scanf("%s",map[i]);
if(p=strchr(map[i],'a'))
{
start.x=i;
start.y=p-map[i];
start.t=;
}
}
ans=bfs(); printf(ans+?"%d\n":"Poor ANGEL has to stay in the * all his life.\n",ans);
}
return ;
}
AC
Acknowledge:罗里罗嗦夫斯基 http://blog.chinaunix.net/uid-21712186-id-1818266.html(我写的“优先队列”随笔也从那借鉴了蛮多)