ACM-ZOJ 1649 BFS 广度优先搜索

//2012-10-09 00:06:16	 Accepted	1649	C++	60ms	392kb
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;

struct Point {  //所在点的信息
    int x, y;
    int time;
    int step;
};

const int inf = 1000000;  //infinity
const int MAX(205);
char map[MAX][MAX];
int minTime[MAX][MAX];  //个点用的最短时间
int N, M;
int ax, ay;
int rx, ry;
queue<Point> q;
int BFS( Point s );

int main() {
    int i(0), j(0);
    while (scanf("%d%d", &N, &M) != EOF) {
        memset(map, 0, sizeof(map) );
        //input and find a & r.
        for ( i = 0; i != N; ++i ) {
            scanf("%s", map[i]);
            for ( j = 0; j != M; ++j ) {
                minTime[i][j] = inf;
                if ( 'a' == map[i][j] )  { ax = i; ay = j; }
                if ( 'r' == map[i][j] )  { rx = i; ry = j; }
            }
        }

        Point start = {rx, ry, 0, 0};
        minTime[rx][ry] = 0;
        int answer = BFS( start );
        if (answer < inf)  printf("%d\n", answer);
        else printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
}

int BFS( Point s ) {
    int move[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
    q.push(s);
    Point head;
    while ( !q.empty() ) {
        int i(0);
        head = q.front();
        q.pop();

        for ( i = 0; i != 4; ++i ) {
            int mx = head.x + move[i][0];
            int my = head.y + move[i][1];
            if (mx < 0 || my < 0 || mx >= N || mx >= M || map[mx][my] == '#')
                continue ;
            Point t = { mx, my, head.time + 1, head.step + 1 };
            if (map[mx][my] == 'x')  ++t.time;
            if (t.time < minTime[mx][my]) {
                minTime[mx][my] = t.time;
                q.push(t);
            }
        }
    }
    return minTime[ax][ay];
}











 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值