Rescue
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 14 Accepted Submission(s) : 7
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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
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
Sample Input
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
Author
Source
BFS广搜 + 优先队列。
题意:从前有一名天使被*了,天使的朋友要去救他,你的任务是输出最短的救援时间。天使的朋友每秒可以走一步,地牢中有守卫,当你遇到守卫的时候需要停留一秒杀死守卫。给你地牢的地图,上面有几种元素,'.'表示路,可以通行。'#'代表墙,无法通行。'r'表示天使的朋友,代表起点。'a'表示天使的位置,代表终点。'x'表示守卫的位置。
思路:因为是求“最短路径”的问题,正好用广搜可以解决。但是与普通广搜不同的是,遇到守卫的时候会多停留一秒。这就会导致队列中优先级的不稳定,所以需要用优先队列,让优先级最高的节点始终在队列最前面。
代码:
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
char a[][];
bool isv[][]; //记录访问过没有
int dx[] = {,,,-};
int dy[] = {,,-,};
int N,M;
int sx,sy,ex,ey;
struct NODE{
int x;
int y;
int step;
friend bool operator < (NODE n1,NODE n2) //自定义优先级。在优先队列中,优先级高的元素先出队列。
{
return n1.step > n2.step; //通过题意可知 step 小的优先级高,需要先出队。
}
};
bool judge(int x,int y)
{
if( x< || y< || x>N || y>M )
return ;
if( isv[x][y] )
return ;
if( a[x][y]=='#' )
return ;
return ;
}
int bfs() //返回从(x,y)开始广搜,到右下角的最短步数,如果无法到达右下角,返回0
{
memset(isv,,sizeof(isv));
priority_queue <NODE> q; //定义一个优先队列
NODE cur,next;
cur.x = sx;
cur.y = sy;
cur.step = ;
isv[sx][sy] = true;
q.push(cur); //第一个元素入队
while(!q.empty()){
cur = q.top(); //队首出队,注意不是front()
q.pop();
if(cur.x==ex && cur.y==ey) //到终点
return cur.step;
for(int i=;i<;i++){
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if( judge(nx,ny) ) //判定
continue;
//可以走
next.x = nx;
next.y = ny;
if(a[nx][ny]=='x')
next.step = cur.step + ;
else
next.step = cur.step + ;
isv[nx][ny] = true;
q.push(next);
}
}
return -;
}
int main()
{
while(cin>>N>>M){
for(int i=;i<=N;i++) //输入
for(int j=;j<=M;j++){
cin>>a[i][j];
if(a[i][j]=='a')
ex=i,ey=j;
else if(a[i][j]=='r')
sx=i,sy=j;
}
int step = bfs();
if(step==-) //不能到达
cout<<"Poor ANGEL has to stay in the * all his life."<<endl;
else
cout<<step<<endl;
}
return ;
}
Freecode : www.cnblogs.com/yym2013