HDU - 1242 - Rescue (BFS)

Rescue

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


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 
 

题意:求从'a'到'r'最少需要多少时间,每移动一格需要1时间,若为'x'则需多花1时间,‘#’为墙,只能上下左右四个方向进行移动

思路:因为有些点耗时为2,所以经过的格子少的时间不一定短,所以每次不是判断该格子是否走过,而是判断这次走过是否比上次更快些(和spfa有点类似)

也可以使用优先队列让步数少的先出

#include
#include
#include
#include
#include
using namespace std;
const int N = 2e2+10;
const int INF = 0x3f3f3f3f;
int n,m,sx,sy,ans;
int dir[4][2] = {0,1,1,0,0,-1,-1,0},dist[N][N],inque[N][N];
char mp[N][N];
bool check(int x,int y){
    if(x<0||x>=n||y>=m||y<0||mp[x][y]=='#') return false;
    return true;
}
void bfs(){
    ans = INF;
    memset(dist,INF,sizeof dist);
    memset(inque,0,sizeof inque);
    queue >q;
    q.push(make_pair(sx, sy));
    inque[sx][sy] = 1; dist[sx][sy] = 0;
    while(!q.empty()){
        int X = q.front().first, Y = q.front().second; q.pop();
        inque[X][Y] = 0;
        if(mp[X][Y]=='r'){
            ans = min(ans, dist[X][Y]);
            continue;
        }
        for(int i=0;i<4;i++){
            int x = X + dir[i][0];
            int y = Y + dir[i][1];
            if(!check(x, y)) continue;
            int cost = 0;
            if(mp[x][y]=='x') cost = 1;
            if(dist[x][y] <= dist[X][Y]+cost+1) continue;
            dist[x][y] = dist[X][Y]+cost+1;
            if(inque[x][y]) continue;
            inque[x][y] = 1;
            q.push(make_pair(x, y));
        }
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0;i



你可能感兴趣的:(广度优先遍历,HDU,最短路)