Rescue
Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9513 Accepted Submission(s): 3477
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.)
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.
7 8 #.#####. #.a#..r. #..#x... ..#..#.# #...##.. .#...... ........
13
AC代码:
#include<iostream>
#include<string.h>
using namespace std;
char p[200][200];
bool flag[200][200];
int m,n;
struct lmx{
int x;
int y;
int time;
};
lmx lm[40000];
bool area(int x,int y)
{
return x>=1&&x<=n&&y>=1&&y<=m;
}
int c[4]={0,1,0,-1};
int d[4]={-1,0,1,0};
int x1,y1,x2,y2;
int bfs(int x,int y)
{
int head=0,rear=1,xx,yy,i;
lm[head].x=x;
lm[head].y=y;
lm[head].time=0;
flag[x][y]=true;
while(head<rear)
{
int xa=lm[head].x;
int ya=lm[head].y;
for(i=0;i<4;i++)
{
xx=xa+c[i];
yy=ya+d[i];
if(area(xx,yy)&&flag[xx][yy]==false)
{
if(xx==x2&&yy==y2) return lm[head].time+1;
else
{
lm[rear].x=xx;
lm[rear].y=yy;
flag[xx][yy]=true;
if(p[xx][yy]=='x') lm[rear].time=lm[head].time+2;
else lm[rear].time=lm[head].time+1;
rear++;
}
}
}
head++;
}
return -1;
}
int main()
{
int i,j;
while(cin>>n>>m)
{
memset(flag,false,sizeof(flag));
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
cin>>p[i][j];
if(p[i][j]=='r') {x1=i;y1=j;}
if(p[i][j]=='a') {x2=i;y2=j;}
if(p[i][j]=='#') flag[i][j]=true;
}
}
int temp=bfs(x1,y1);
if(temp!=-1) cout<<temp<<endl;
else cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
return 0;
}