輸入數據比較難理解:
A B C可以理解爲對應輸入的A->x軸的單位長度,B->z軸的單位長度(方向向向下),C->y軸的單位長度.
注:左上后角作爲座標原點。
//第一塊
1 1 1 1
1 0 0 1
0 1 1 1
//第二塊
0 0 0 0
0 1 1 0
0 1 1 0
//第三塊
解法:廣搜,隊列
峯注:進隊列後必須馬上標記。
ac代碼:
#include<iostream> #include<stdio.h> #include<queue> using namespace std; struct node { int x,y,z; int t; }; const int m=51; int x,y,z,t; int map[m][m][m],dir[6][3]={ 0, 0, 1, 0, 0,-1, 0, 1, 0, 0,-1, 0, 1, 0, 0, -1, 0, 0}; //正方體六個面的方向,注:z軸方向:向下 // 方向:下,上,右,左,前,後 int check(int i,int j,int k) //判斷是否出界,(即是否在正方體內) { if(i>=0&&i<x&&j>=0&&j<y&&k>=0&&k<z) { return 1; } else return 0; } int main() { queue<node>q; node temp; int n; int i,j,k; while(cin>>n) { for(int l=0;l<n;l++) { cin>>x>>y>>z>>t; for(i=0;i<x;i++) //三個for()循環輸入 { for(j=0;j<y;j++) { for(k=0;k<z;k++) { scanf("%d",&map[i][j][k]); } } } temp.x=0; temp.y=0; temp.z=0; temp.t=0; q.push(temp); //座標原點進隊列,初始化 map[q.front().x][q.front().y][q.front().z]=1; //特別注意:進隊列後必須標記爲牆 while(!q.empty()) { if(q.front().t<t&&q.front().x==x-1&&q.front().y==y-1&&q.front().z==z-1) { cout<<q.front().t<<endl; break; } //(x-1,y-1,z-1)即右下前座標,滿足提前跳出循環 for(int a=0;a<6;a++) { i=q.front().x+dir[a][0]; j=q.front().y+dir[a][1]; k=q.front().z+dir[a][2]; if(check(i,j,k)) { if(map[i][j][k]==0) { temp.x=i; temp.y=j; temp.z=k; temp.t=q.front().t+1; map[i][j][k]=1; //特別注意:進隊列後必須標記爲牆 q.push(temp); } } } //一個立方體有六個方向,第一個if()判斷是否出界, //第二個if()判斷是否爲牆 map[q.front().x][q.front().y][q.front().z]=1; q.pop(); } if(q.empty()) cout<<"-1"<<endl; else { while(!q.empty()) { q.pop(); } } }//end-for() }//end-while return 0; } 注:不懂請留言。