Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30270 Accepted Submission(s): 10647
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
经典的优先队列广搜题
#include
#include
#include
#include
using namespace std;
const int maxn = 205;
typedef struct node
{
int x,y;
int step;
friend bool operator < (const node &b,const node &a) //优先队列的规定 重载运算符 < ,不可更变为>
{
return b.step>a.step; // 根据cmp中排序,是从大到小排序,所以队列的 top(最后一位) 就是最小的。
}
//或者
/* bool operator < (const node &a) const //优先队列的规定 重载运算符 < ,不可更变为>. 注意两个const。
{
return step>a.step;
}
*/
}point;
point start;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
char maze[maxn][maxn];
int row,col;
//int a[10]={5,8,9,1,2,3,4,6,5,2};
void init()
{
memset(maze,0,sizeof(maze));
for(int i=1;i<=row;i++)
for(int j=1;j<=col;j++)
{
cin>>maze[i][j];
if(maze[i][j]=='a')
start={i,j,0};
}
}
int bfs()
{
priority_queue qu;
qu.push(start);
maze[start.x][start.y]='#';
while(!qu.empty())
{
point v = qu.top();
qu.pop();
for(int i=0;i<4;i++)
{
int mx = v.x+dir[i][0];
int my = v.y+dir[i][1];
if(mx<1||mx>row||my<1||my>col||maze[mx][my]=='#') continue;
if(maze[mx][my]=='r') return v.step+1;
point to={mx,my,v.step+1};
if(maze[mx][my]=='x')
to.step++;
maze[mx][my]='#';
qu.push(to);
}
}
return -1;
}
int main()
{
while(cin>>row>>col)
{
init();
int ans= bfs();
if(ans==-1)
cout<<"Poor ANGEL has to stay in the prison all his life."<else cout<return 0;
}