胜利大逃亡

题目描述:

Ignatius被魔王抓走了,有一天魔王出差去了,这可是Ignatius逃亡的好机会.魔王住在一个城堡里,城堡是一个A*B*C的立方体,可以被表示成A个B*C的矩阵,刚开始Ignatius被关在(0,0,0)的位置,离开城堡的门在(A-1,B-1,C-1)的位置,现在知道魔王将在T分钟后回到城堡,Ignatius每分钟能从一个坐标走到相邻的六个坐标中的其中一个.现在给你城堡的地图,请你计算出Ignatius能否在魔王回来前离开城堡(只要走到出口就算离开城堡,如果走到出口的时候魔王刚好回来也算逃亡成功),如果可以请输出需要多少分钟才能离开,如果不能则输出-1.

输入:

输入数据的第一行是一个正整数K,表明测试数据的数量.每组测试数据的第一行是四个正整数A,B,C和T(1<=A,B,C<=50,1<=T<=1000),它们分别代表城堡的大小和魔王回来的时间.然后是A块输入数据(先是第0块,然后是第1块,第2块......),每块输入数据有B行,每行有C个正整数,代表迷宫的布局,其中0代表路,1代表墙。

输出:

对于每组测试数据,如果Ignatius能够在魔王回来前离开城堡,那么请输出他最少需要多少分钟,否则输出-1.

样例输入:
1
3 3 4 20
0 1 1 1
0 0 1 1
0 1 1 1
1 1 1 1
1 0 0 1
0 1 1 1
0 0 0 0
0 1 1 0
0 1 1 0 
样例输出:
11

分析:
首先,使用如下结构体保存每一个状态:
struct VertexInfo{
int x , y , z; //位置坐标
int t; //所需时间
};
其次,为了实现各个状态按照其被查找到的顺序依次转移扩展,我们需要使用一个队列。即将每次扩展得到的新状态放入队列中,待排在其之前的状态都被扩展完成后,该状态才能得到扩展。
最后,为了防止对无效状态的搜索,我们需要一个标记数组 mark[x][y][z],当已经得到过包含坐标( x, y, z)的状态后,即把 mark[x][y][z]置为 true,当下次再由某状态扩展出包含该坐标的状态时,则直接丢弃,不对其进行任何处理。
#include "stdafx.h"
#include <stdio.h>
#include <queue>
using namespace std;

const int MAXSIZE = 50;

bool mark[MAXSIZE][MAXSIZE][MAXSIZE];
int cube[MAXSIZE][MAXSIZE][MAXSIZE];
int a, b, c, t;

struct VertexInfo{
    int x;
    int y;
    int z;
    int t;
};

queue <VertexInfo> que;

int go[][3] = {
    { 1, 0, 0},
    {-1, 0, 0},
    {0, 1, 0},
    {0, -1, 0},
    {0, 0, 1},
    {0, 0, -1}
};

int BFS(int a, int b, int c)
{
    VertexInfo start;
    start.x = 0;
    start.y = 0;
    start.z = 0;
    start.t = 0;
    mark[0][0][0] = true;
    que.push(start);

    while (que.empty() != true)
    {
        VertexInfo nowState = que.front();
        que.pop();
        for (int i = 0; i < 6; i++)
        {
            int nx = nowState.x + go[i][0];
            int ny = nowState.y + go[i][1];
            int nz = nowState.z + go[i][2];
            if (nx < 0 || nx >= a || ny < 0 || ny >= b || nz < 0 || nz >= c)
                continue;
            if (cube[nx][ny][nz] == 1 || mark[nx][ny][nz] == true) continue;
            VertexInfo newState;
            newState.x = nx;
            newState.y = ny;
            newState.z = nz;
            newState.t = nowState.t + 1;
            que.push(newState);
            mark[nx][ny][nz] = true;
            if (nx == a - 1 && ny == b - 1 && nz == c - 1)
                return newState.t;
        }
    }

    return -1;
}

int main()
{
    int n;
    scanf("%d", &n);
    while (n--)
    {
        scanf("%d%d%d%d", &a, &b, &c, &t);
        for (int i = 0; i < a; i++)
        for (int j = 0; j < b; j++)
        for (int k = 0; k < c; k++)
        {
            scanf("%d", &cube[i][j][k]);
            mark[i][j][k] = false;
        }

        while (que.empty() != true)
            que.pop();

        int result = BFS(a, b, c);
        if (result <= t)
            printf("%d
",result);
        else
            printf("-1
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tgycoder/p/5032826.html