#include<iostream> #include<queue> using namespace std; bool cas[52][52][52];//存map int visited[52][52][52]; int step[6][3]={{1,0,0},{0,1,0},{0,0,1},{-1,0,0},{0,-1,0},{0,0,-1}};//六个方向 int a,b,c; struct loc{ int x,y,z; int step; }; int bfs( ){ queue<loc> que; loc temp,now; temp.x=0; temp.y=0; temp.z=0; temp.step=0; int x,y,z; que.push(temp); while(!que.empty()){ temp=que.front(); if(temp.x==a-1 && temp.y==b-1 && temp.z==c-1) return temp.step; que.pop(); for(int i=0;i<6;i++){ x=temp.x+step[i][0]; y=temp.y+step[i][1]; z=temp.z+step[i][2]; if(x>=0 && x<a && y>=0 && y<b && z>=0 && z<c && cas[x][y][z]==0 && !visited[x][y][z]){ now.x=x; now.y=y; now.z=z; now.step=temp.step+1; //每一个元素对应一层 , 一层有可能有多个元素 而步数step 是过一层+1 que.push(now); visited[x][y][z]=1; } } } return -1;//最后一个错误找不到时一定要返回一个-1 } int main(){ int k,t; int i,j,s; scanf("%d",&k); while(k--){ scanf("%d%d%d%d",&a,&b,&c,&t); for(i=0;i<a;i++){ for(j=0;j<b;j++){ for(s=0;s<c;s++){ scanf("%d",&cas[i][j][s]); visited[i][j][s] = false; } } } visited[0][0][0] = true; int ans=bfs(); printf("%d/n",ans<=t? ans:-1); } return 1; } http://acm.hdu.edu.cn/showproblem.php?pid=1253 用BFS 找出最短出路 关键每一层有多个元素 step+=层