hdu 1253bfs勝利大逃亡

勝利大逃亡

 

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 23912    Accepted Submission(s): 9172

 

 

Problem Description

Ignatius被魔王抓走了,有一天魔王出差去了,這可是Ignatius逃亡的好機會.

 

魔王住在一個城堡裏,城堡是一個A*B*C的立方體,可以被表示成A個B*C的矩陣,剛開始Ignatius被關在(0,0,0)的位置,離開城堡的門在(A-1,B-1,C-1)的位置,現在知道魔王將在T分鐘後回到城堡,Ignatius每分鐘能從一個座標走到相鄰的六個座標中的其中一個.現在給你城堡的地圖,請你計算出Ignatius能否在魔王回來前離開城堡(只要走到出口就算離開城堡,如果走到出口的時候魔王剛好回來也算逃亡成功),如果可以請輸出需要多少分鐘才能離開,如果不能則輸出-1.

 

 

 

 

 

Input

輸入數據的第一行是一個正整數K,表明測試數據的數量.每組測試數據的第一行是四個正整數A,B,C和T(1<=A,B,C<=50,1<=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的裸應用,三維就有6個方向。而且不用認xyz軸的。

源代碼:

#include <iostream>

#include <stdio.h>

#include <string.h>

#include <string>

#include <queue>

using namespacestd;

struct node

{

     intx,y,z;

};

int t,a,b,c;

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

int map[55][55][55];

int used[55][55][55];

 

bool judge(intx,inty,intz)

{

     if(x>= a||x < 0||y>= b || y < 0||z>= c||z < 0)

         returnfalse;

     if(map[x][y][z])

         returnfalse;

     if(used[x][y][z]> -1)

         returnfalse;

     returntrue;

}

 

void bfs()

{

     node tt,tp;

     tt.x = 0;

     tt.y = 0;

     tt.z = 0;

     queue<node> q;

     q.push(tt);

     used[0][0][0]= 0;

     while(!q.empty())

     {

         tp =q.front();

         q.pop();

         for(int  i = 0;i < 6;i++)

         {

              tt.x= tp.x + dir[i][0];

              tt.y= tp.y + dir[i][1];

              tt.z= tp.z + dir[i][2];

              if(!judge(tt.x,tt.y,tt.z))

                   continue;

              used[tt.x][tt.y][tt.z]= used[tp.x][tp.y][tp.z] + 1;

              if(tt.x== a-1 && tt.y == b-1 && tt.z == c-1

                   &&used[tt.x][tt.y][tt.z]<= t)

                   return;

              if(used[tt.x][tt.y][tt.z]>= t)

                   continue;

              q.push(tt);

         }

     }

}

int main()

{

     intn;

     cin>> n;

     for(inti = 0;i < n;i++)

     {

         scanf("%d%d%d%d",&a,&b,&c,&t);

         for(inti = 0;i < a;i++)

              for(intj = 0;j < b;j++)

                   for(intk = 0;k < c;k++)

                   {

                       used[i][j][k]= -1;

                       scanf("%d",&map[i][j][k]);

                   }

 

         bfs();

         printf("%d\n",used[a-1][b-1][c-1]);

     }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章