TOJ 1335 优先队列

1335: 营救天使

时间限制(普通/Java):1000MS/10000MS 内存限制:65536KByte

描述

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.)

输入

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, “x” stands for a guard, and “r” stands for each of Angel’s friend.

Process to the end of the file.

输出

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.”

样例输入

7 8
#.#####.
#.a#…r.
#…#x…
…#…#.#
#…##…
.#…

样例输出

13

题目来源

ZOJ Monthly 2003
解题思路:这题一开始没用优先队列,WA了n次,一直WA的可以看看下面的案例,并且这题只有一个小朋友,可以百度一下C++队列的一些用法。
4 3
…r
.#x
.#x
.ax

3

3 2
a#
xr
r#

6

#include 
#include 
#include 
#include 
using namespace std;
char a[201][201];
int dir[4][2]= {0,1,0,-1,1,0,-1,0};	//定义四个方向
int ax,ay,n,m;
struct node{
    int x,y,step;
    friend bool operator < (node a,node b){ //重载了队列的优先级,step小的优先级高
        return  a.step > b.step;
    }
}now,next;
int bfs(int x,int y){
    priority_queue<node>q;			
    now.x=x, now.y=y, now.step=0;	
    q.push(now);		//设置第一个点属性并且压入队列
    a[x][y]='#';		//标记已走过
    while(!q.empty()){
    	now = q.top();	//队头赋给now
        q.pop();		//弹出
        for(int i=0 ; i<4 ; i++){	//四个方向遍历
            int nx = now.x + dir[i][0];
            int ny = now.y + dir[i][1];
            if(nx>=0&&nx<n&&ny>=0&&ny<m&&a[nx][ny]!='#'){	//条件满足
                 next;
                next.x=nx, next.y=ny, next.step=now.step+1;	
                if(a[nx][ny]=='x')	// 当遇到陷阱时时间要加1
                    ++next.step;
                if(a[nx][ny]=='r'){ // 天使位置,输入步数
                	cout << next.step << endl;
                	return 0;             	
                }                    
                a[nx][ny]='#';
                q.push(next);
            }
        }
    }
    return 1;
}
int main(){
    while(cin >> n >> m){
        for(int i=0 ; i<n ;i++){
            getchar();
            for(int j=0 ; j<m ;j++){	//输入标记
                a[i][j]=getchar();
                if(a[i][j]=='a')  ax=i, ay=j;
            }
        }
        if(bfs(ax,ay))
            cout << "Poor ANGEL has to stay in the prison all his life." << endl;
    }
}

你可能感兴趣的:(广度优先搜索)