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
我的是bfs,网上还有其他方法(优先队列和dfs,bfs),但是感觉还是我的bfs最快了
提交4次基本都是10ms
在bfs拓展入队的时候加入一点dp的思想,当前这个点被第二访问时,选择最短的步数即可
还有就是用pair封装坐标可能好看点吧。。。QAQ
典型的BFS模板题
#include
#include
#include
using namespace std;
const int N=201;
typedef pair p;//用pari封装一下坐标
typedef queue q;
int m,n;
char s[N][N];
int dir[4][2]={0,1,1,0,-1,0,0,-1};
int num[N][N];
int a,b;
int e1,e2;//起点
int ans;
int f1,f2;//终点
void bfs()
{
int step=0,x,y;
q qu;
p pa;
pa = make_pair(a,b);
qu.push(pa);
while(!qu.empty())
{
pa = qu.front();
qu.pop();
x=pa.first,y=pa.second;
if( x== e1 && y== e2)
{
//printf("num=%d\n",num[x][y]);
if(ans>num[x][y]) ans=num[x][y];
//return;
}
for(int i=0;i<4;i++)
{
int xx,yy;
xx=x+dir[i][0];
yy=y+dir[i][1];
if(xx>=0 && yy>=0 &&xx