HDU1253 胜利大逃亡 BFS 胜利大逃亡

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 15   Accepted Submission(s) : 7

Font: Times New Roman | Verdana | Georgia

Font Size:

Problem Description

Ignatius被魔王抓走了,有一天魔王出差去了,这但是Ignatius逃亡的好机会.

魔王住在一个城堡里,城堡是一个A*B*C的立方体,能够被表示成A个B*C的矩阵,刚開始Ignatius被关在(0,0,0)的位置,离开城堡的门在(A-1,B-1,C-1)的位置,如今知道魔王将在T分钟后回到城堡,Ignatius每分钟能从一个坐标走到相邻的六个坐标中的当中一个.如今给你城堡的地图,请你计算出Ignatius是否能在魔王回来前离开城堡(仅仅要走到出口就算离开城堡,假设走到出口的时候魔王刚好回来也算逃亡成功),假设能够请输出须要多少分钟才干离开,假设不能则输出-1.

HDU1253 胜利大逃亡 BFS
胜利大逃亡

Input

输入数据的第一行是一个正整数K,表明測试数据的数量.每组測试数据的第一行是四个正整数A,B,C和T(1<=A,B,C<=50,1&lt;=T<=1000),它们分别代表城堡的大小和魔王回来的时间.然后是A块输入数据(先是第0块,然后是第1块,第2块......),每块输入数据有B行,每行有C个正整数,代表迷宫的布局,当中0代表路,1代表墙.(假设对输入描写叙述不清楚,能够參考Sample Input中的迷宫描写叙述,它表示的就是上图中的迷宫)

特别注意:本题的測试数据很大,请使用scanf输入,我不能保证使用cin能不超时.在本OJ上请使用Visual C++提交.

Output

对于每组測试数据,假设Ignatius可以在魔王回来前离开城堡,那么请输出他最少须要多少分钟,否则输出-1.

Sample Input

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

Sample Output

11

三维的地图, 所以用三维数组。
其它和简单的BFS是一样的,方向就加了上下两个方向。
代码:
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
#define M 100
struct node{
int x,y,z,time;
};
int map[M][M][M],a,b,c,T;
int dis[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
int DFS(int x,int y,int z)
{
    int i;
    node t,temp;
    queue<node>Q;
    bool vis[M][M][M];
    memset(vis,0,sizeof(vis));
    t.x=x;t.y=y;t.z=z;t.time=0;
    Q.push(t);
    vis[t.x][t.y][t.z]=1;
    while(!Q.empty())
    {
        t=Q.front();
        Q.pop();
        if(t.x==b-1 && t.y==c-1 && t.z==a-1)
        {

            return t.time;
        }
        else
        {
            for(i=0;i<6;i++)
            {
                temp.x=t.x+dis[i][0];
                temp.y=t.y+dis[i][1];
                temp.z=t.z+dis[i][2];
                temp.time=t.time+1;
                //printf(" %d %d %d",temp.x,temp.y,temp.z);
                if(temp.x>=0 &&temp.x<b && temp.y>=0 && temp.y<c && temp.z>=0 && temp.z<a)
                {//printf("ok
");
                if(!vis[temp.x][temp.y][temp.z] && map[temp.x][temp.y][temp.z]==0)
                {
                    vis[temp.x][temp.y][temp.z]=1;
                    Q.push(temp);
                }

                }
            }
        }
    }
    return 9999;
}
int main()
{
    int i,j,k,C;
    while(scanf("%d",&C)!=EOF)
    {
     while(C--)
    {
    scanf("%d%d%d%d",&a,&b,&c,&T);
    for(k=0;k<a;k++)
    for(i=0;i<b;i++)
    for(j=0;j<c;j++)
    scanf("%d",&map[i][j][k]);
    i=DFS(0,0,0);
    if(i>T) printf("-1
");
    else printf("%d
",i);
    }
    }
    return 0;
}


版权声明:本文博客原创文章。博客,未经同意,不得转载。