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
AC代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef long long ll;
const int inf = 0x3f3f3f3f;
using namespace std;
#define maxsize 200
char e[205][205];
int book[205][205];
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int n,m,ans,startx,starty;
void dfs(int a,int b,int cur){ //有多个r 应该从 a出发寻找最近的r
int ta,tb;
if(cur >= ans) return ;
if(e[a][b] == 'r')
{
ans = cur;
return ;
}
for(int i = 0;i < 4;i++)
{
ta = a + dir[i][0];
tb = b + dir[i][1];
if(ta >= 0 && tb >= 0 && ta < n && tb < m && !book[ta][tb] && e[ta][tb] != '#')
{
book[ta][tb] = 1;
if(e[ta][tb] == 'x') dfs(ta,tb,cur + 2);
else dfs(ta,tb,cur + 1);
book[ta][tb] = 0;
}
}
return ;
}
int main(){
while(cin >> n >> m)
{
getchar();
int t = 0;
ans = inf;
memset(book,0,sizeof(book));
for(int i = 0;i < n;i++)
{
for(int j = 0;j < m;j++)
{
scanf("%c",&e[i][j]);
if(e[i][j] == 'a')
{
startx = i;
starty = j;
}
}
getchar();
}
book[startx][starty] = 1;
dfs(startx,starty,0);
if(ans == inf) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",ans);
}
return 0;
}