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
这道题对于小白的我可是花了不少功夫呀,最后一直在修改一个bug,就是找不到,实在令人头痛,现在好了,把这道题完全吃透了。
分析:对于a是固定的,我们通过移动r来到达a的位置,每移动一步就要花费一分钟(暂且这样认为)但是如果遇到x就要花费两分钟,这样的话思路就有了,只需要判断是否是x就行了,一个if语句就搞定了,问题是什么呢,我的错误就错在又用了一个if语句来判断是否是’.‘,因此就少考虑一种情况,当到达目的地a时,没有加步数,所以每次计算结果老是少1,小白头痛一个多小时,最后找到了。
还有如何控制r的移动呢,那就需要定义一个二维数组,通过加减的方式来控制,代码上有体现。当然结构体还是要有的,结构体来存储步数,以及r的位置。然后再重载以步数按升序排列(优先队列)。
对了还有就是,把变量定义在函数外面,在每个函数中可以直接使用,无需用指针。代码如下:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MAXN=1e4+10;
struct node{
int x,y,step;
bool friend operator<(node a,node b){
return a.step>b.step;
}//重载函数以步数最少为最优
};
int a1,b1,c,d,m,n,flag,r[210][210];
char str[210][210];
int r2[2][4]={{0,1,0,-1},{1,0,-1,0}};//控制方向的移动
priority_queue <node> p;
void BFS(int c,int d){
flag=0;
node new1,next;
new1.x=c;
new1.y=d;
new1.step=0;
p.push(new1);
while(!p.empty()){
next=p.top();
p.pop();
if(next.x==m&&next.y==n){
flag=1;
break;
}
for(int i=0;i<4;i++){
new1.x=next.x+r2[0][i];
new1.y=next.y+r2[1][i];
if(new1.x>=0 && new1.x<a1 && new1.y>=0 && new1.y<b1 && !r[new1.x][new1.y]&&str[new1.x][new1.y]!='#'){
if(str[new1.x][new1.y]=='x'){
new1.step=next.step+2;
}
else{
new1.step=next.step+1;
}
r[new1.x][new1.y]=1;
p.push(new1);
}
}
}
if(flag)
printf("%d\n",next.step);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main(){
int i,j;
while(scanf("%d%d",&a1,&b1)!=EOF){
memset(r,0,sizeof(r));
memset(str,0,sizeof(str));
for(i=0;i<a1;i++){
getchar();
for(j=0;j<b1;j++){
scanf("%c",&str[i][j]);
if(str[i][j]=='a'){
m=i;
n=j;
}
if(str[i][j]=='r'){
c=i;
d=j;
}
}
}
BFS(c,d);
}
return 0;
}
典型的BFS的题目,加油!