Hdu1242 Rescue 【简单bfs】

http://acm.hdu.edu.cn/showproblem.php?pid=1242

因为有多个营救的人,而只有一个被营救的人,所以以被营救的人为起点进行bfs。(代码中用ma[][]数组进行标记,ma[i][j] 表示的是起始坐标(sx,sy)(i,j)的最短距离)

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template <class T> void checkmin(T &t,T x) {if(x < t) t = x;}
template <class T> void checkmax(T &t,T x) {if(x > t) t = x;}
template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;}
template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;}
typedef pair <int,int> PII;
typedef pair <double,double> PDD;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++)
#define inf (1<<29)
const int N = 220;
int ma[N][N] , n , m;
char maze[N][N];
struct node {
    int x , y;
};
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
int sx , sy;
void find() {
    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++)
    if(maze[i][j] == 'a') {
        sx = i , sy = j ;
        return;
    }
}
bool inmap(int x,int y) {
    return x>=0&&x<n&&y>=0&&y<m;
}
queue <node> q;
void bfs() {
    node u , v;
    while(!q.empty()) q.pop();
    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++) {
        ma[i][j] = -1;
    }
    ma[sx][sy] = 0;
    u.x = sx , u.y = sy;
    q.push(u);
    while(!q.empty()) {
        u = q.front(); q.pop();
        for(int i=0;i<4;i++) {
            int x = u.x + dir[i][0];
            int y = u.y + dir[i][1];
            if(!inmap(x,y) || maze[x][y] == '#') continue;
            int del = maze[x][y] == 'x' ? 2 : 1;
            if(ma[x][y] == -1 || ma[u.x][u.y]+del < ma[x][y]) {
                ma[x][y] = ma[u.x][u.y] + del;
                v.x = x , v.y = y;
                q.push(v);
            }
        }
    }
}
int main() {
    while(~scanf("%d%d",&n,&m)) {
        for(int i=0;i<n;i++) scanf("%s",maze[i]);
        find();
        bfs();
        int ans = inf;
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) {
            if(maze[i][j] == 'r' && ma[i][j] != -1) {
                checkmin(ans , ma[i][j]);
            }
        }
        if(ans == inf) puts("Poor ANGEL has to stay in the prison all his life.");
        else printf("%d\n" , ans);
    }
    return 0;
}

 

 

posted @ 2013-03-30 02:10  aiiYuu  阅读(141)  评论(0编辑  收藏  举报