HDU 勝利大逃亡 (bfs)
題面
gnatius被魔王抓走了,有一天魔王出差去了,這可是Ignatius逃亡的好機會.
魔王住在一個城堡裡,城堡是一個ABC的立方體,可以被表示成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,只不過這題的具體操作需要多一個維度,所以開三維陣列就好了。
程式碼實現
#include <iostream> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <list> #include <map> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <numeric> #include<vector> #include <functional> using namespace std; typedef long long ll; const int N=1000000+10; int maze[55][55][55]; int moves[6][3]={{1,0,0},{0,0,1},{0,1,0},{-1,0,0},{0,-1,0},{0,0,-1}}; int t,a,b,c,times,flags; struct node { int x,y,z,step; }; void bfs () { flags=0; queue<node> q; node now,temp; now.x=0,now.y=0,now.z=0,now.step=0; maze[0][0][0]=1; q.push(now); while (!q.empty()) { now=q.front(); q.pop(); if (now.x==a-1&&now.y==b-1&&now.z==c-1) { flags=1; break; } else { for (int i=0;i<6;i++) { int nx=now.x+moves[i][0]; int ny=now.y+moves[i][1]; int nz=now.z+moves[i][2]; temp.x=nx, temp.y=ny, temp.z=nz, temp.step=now.step+1; if (nx>=0&&ny>=0&&nz>=0&&nx<a&&ny<b&&nz<c&&maze[nx][ny][nz]==0) { if (temp.step+a-1-temp.x+b-1-temp.y+c-1-temp.z>times) { maze[nx][ny][nz]=1; continue; } q.push (temp); maze[nx][ny][nz]=1; } } } } if (!flags) cout<<-1<<endl; else cout<<now.step<<endl; } int main() { while (cin>>t) { while (t--) { cin>>a>>b>>c>>times; for (int i=0;i<a;i++) for (int j=0;j<b;j++) for (int k=0;k<c;k++) { scanf ("%d",&maze[i][j][k]); } bfs (); } } return 0; }