Rescue+BFS

来源:互联网 发布:飓风bt软件 编辑:程序博客网 时间:2024/05/22 11:37

Rescue

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10650    Accepted Submission(s): 3905


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
 

Author
CHEN, Xue
 

Source
ZOJ Monthly, October 2003
 

Recommend
Eddy
 
BFS搜索:
从‘r’为止开始,往四个方向搜索,知道找到‘a’或则地图被搜索完毕,
最后只要判min1是否改变了值,就可以了
#include<iostream>#include<queue>using namespace std;typedef struct infor{int x;int y;int time;}infor;queue<infor>q;char s[202][202];int step[202][202];int n,m,move[4][2]={{-1,0},{0,1},{1,0},{0,-1}},start,end;int min1;bool inmap(int x,int y){if(x>=0&&x<n&&y>=0&&y<m)return true;elsereturn false;}void BFS(){infor a;a.x=start;a.y=end;a.time=0;q.push(a);while(!q.empty()){infor b=q.front();q.pop();for(int i=0;i<4;i++){infor c=b;c.x+=move[i][0];c.y+=move[i][1];c.time++;if(inmap(c.x,c.y)&&s[c.x][c.y]!='#'&&c.time<step[c.x][c.y]){if(s[c.x][c.y]=='a'){min1=min1>c.time?c.time:min1;}if(s[c.x][c.y]=='x'){c.time++;step[c.x][c.y]=c.time;q.push(c);}if(s[c.x][c.y]=='.'){step[c.x][c.y]=c.time;q.push(c);}}}}}int main(){while(cin>>n>>m){min1=1000000;int i,j;for(i=0;i<n;i++)for(j=0;j<m;j++){cin>>s[i][j];step[i][j]=100000;if(s[i][j]=='r'){start=i;end=j;}}BFS();if(min1==1000000)cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;elsecout<<min1<<endl;}return 0;}

 
原创粉丝点击