hdu2216

来源:互联网 发布:好的淘宝女装店铺推荐 编辑:程序博客网 时间:2024/06/08 15:58

/*
 * File:   hdu2216.cpp
 * Author: chenjiang
 *
 * Created on 2010年5月9日, 下午7:33
 */

#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <math.h>
using namespace std;
#define _max 25
#define inf 214748364
char mapmap[_max][_max];
int g[_max][_max][_max][_max];

struct node {
    int sx, sy;
    int zx, zy;
    int step;
} start;
int next1[4][2] = {
    {0, -1},
    {0, 1},
    {1, 0},
    {-1, 0},
};
int n, m;

void Init() {
    int i, j, k, s;
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
            for (k = 0; k < n; k++) {
                for (s = 0; s < m; s++) {
                    g[i][j][k][s] = inf;
                }
            }
        }
    }
}

void bfs() {
    int i, j, k, s;
    int ans = inf;
    Init();
    start.step = 0;
    queue<node>Q;
    Q.push(start);
    while (!Q.empty()) {
        node temp = Q.front();
        Q.pop();
        if (temp.step >= g[temp.zx][temp.zy][temp.sx][temp.sy]) {
            continue;
        }
        g[temp.zx][temp.zy][temp.sx][temp.sy] = temp.step;
        if (abs(temp.zx - temp.sx) + abs(temp.zy - temp.sy) <= 1) {
            if (temp.step < ans) {
                ans = temp.step;
            }
            continue;
        }
        for (i = 0; i < 4; i++) {
            node t;
            int zx, zy, sx, sy;
            zx = temp.zx + next1[i][0];
            zy = temp.zy + next1[i][1];
            if (zx >= 0 && zx < n && zy >= 0 && zy < m && mapmap[zx][zy] != 'X') {
                sx = temp.sx - next1[i][0];
                sy = temp.sy - next1[i][1];
                if (sx >= 0 && sx < n && sy >= 0 && sy < m && mapmap[sx][sy] != 'X') {
                    t.step = temp.step + 1;
                    t.zx = zx;
                    t.zy = zy;
                    t.sx = sx;
                    t.sy = sy;
                    Q.push(t);
                } else {
                    t.step = temp.step + 1;
                    t.zx = zx;
                    t.zy = zy;
                    t.sx = temp.sx;
                    t.sy = temp.sy;
                    Q.push(t);
                }
            }
        }
    }
    if (ans == inf) {
        cout << "Bad Luck!" << endl;
    } else {
        cout << ans << endl;
    }
}

/*
 *
 */
int main(int argc, char** argv) {

    int i, j;
    while (cin >> n >> m) {
        for (i = 0; i < n; i++) {
            cin >> mapmap[i];
            for (j = 0; j < m; j++) {
                if (mapmap[i][j] == 'Z') {
                    start.zx = i;
                    start.zy = j;
                }
                if (mapmap[i][j] == 'S') {
                    start.sx = i;
                    start.sy = j;
                }
            }
        }
        bfs();
    }
    return (EXIT_SUCCESS);
}

 

原创粉丝点击