POJ 1242 Rescue
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
公主被恶魔抓走啦!
公主的小伙伴都来救公主了,赶快算算哪个小伙伴先找到公主
#表示墙,. 表示路,a表示公主,r表示公主的小伙伴,x表示恶魔的守卫。小伙伴向前后左右走一步需要一个单位时间,遇到守卫,还要打到守卫,这还需要一个单位时间。到底哪个公主最少需要经过多次时间才能被小伙伴找到呢?
这道题使用宽搜+优先队列,由于有多个小伙伴,求最少时间就反过来算,让公主走,看看公主至少走几步才能遇到小伙伴。简单的深搜,不过记得要使用优先队列哦~
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const long long M = 205;
const int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int n, m, ans, vis[M][M];
char map[M][M];
struct Coor
{
int x, y, ans;
friend bool operator < (const Coor &a, const Coor &b)
{
return a.ans > b.ans;
}
};
int bfs(int sx, int sy)
{
int i;
ans = 0;
priority_queue q;
Coor t, now;
memset(vis, 0, sizeof(vis));
vis[sx][sy] = 1;
t.x = sx;
t.y = sy;
t.ans = 0;
q.push(t);
while(!q.empty())
{
now = q.top();
q.pop();
if (map[now.x][now.y] == 'r')
{
return now.ans;
}
for (i = 0; i < 4; i++)
{
t.x = now.x + dir[i][0];
t.y = now.y + dir[i][1];
if (t.x < 0 || t.y < 0 || t.x >= n || t.y >= m || map[t.x][t.y] == '#' || vis[t.x][t.y])
{
continue;
}
t.ans = now.ans + 1;
if (map[t.x][t.y] == 'x')
{
t.ans++;
}
vis[t.x][t.y] = 1;
q.push(t);
}
}
return -1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt", "r", stdin);
#endif
int i, j, sx, sy, ans;
while(~scanf("%d%d", &n, &m))
{
memset(vis, 0, sizeof(vis));
memset(map, 0, sizeof(map));
getchar();
for (i = 0; i < n; i++)
{
gets(map[i]);
}
for (i = 0; i < n; i++)
{
for (j = 0;j < m; j++)
{
if ('a' == map[i][j])
{
sx = i;
sy = j;
break;
}
}
}
ans = bfs(sx, sy);
if (ans != -1)
{
cout << ans << endl;
}
else
{
cout << "Poor ANGEL has to stay in the prison all his life.\n";
}
}
return 0;
}