题目链接:
题目描述:
Problem 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."
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<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std; struct node{
int x,y,s;
bool operator < (const node &a) const {
return a.s<s;};
};
bool bk[][];
char map[][];
void bfs(int sx,int sy);
int n,m,ex,ey; int main()
{
//freopen("E:\\testin.txt","r",stdin);
int sx,sy;
while(scanf("%d%d",&n,&m) != EOF){
memset(map,,sizeof(map)); for(int i=;i<=n;i++){
for(int j=;j<=m;j++){
scanf(" %c",&map[i][j]);
if(map[i][j] == 'r')
{
sx=i;sy=j;
}
}
} bfs(sx,sy);
}
return ;
} void bfs(int sx,int sy){
priority_queue<struct node> q;
struct node head,temp,temp1;
memset(bk,,sizeof(bk));
head.x=sx;
head.y=sy;
head.s=;
int next[][]={-,,,,,,,-};
q.push(head);
bk[sx][sy]=;
int flag=,tx,ty; while(!q.empty()){
temp=q.top();q.pop(); for(int i=;i<;i++){
tx=temp.x+next[i][];
ty=temp.y+next[i][]; if(tx < || tx > n || ty < || ty > m || map[tx][ty] == '#' || map[tx][ty] == 'r')
continue;
if(bk[tx][ty] == ){
bk[tx][ty] = ; if(map[tx][ty] == '.'){
temp1.x=tx;
temp1.y=ty;
temp1.s=temp.s+;
q.push(temp1);
}
if(map[tx][ty] == 'x'){
temp1.x=tx;
temp1.y=ty;
temp1.s=temp.s+;
q.push(temp1);
}
if(map[tx][ty] == 'a'){
flag=;
printf("%d\n",temp.s+);
}
}
}
}
if(flag == )
printf("Poor ANGEL has to stay in the * all his life.\n");
}