注意剪枝,否则会超时的, 还有一处可以优化,就是输入的时候可以使用输入外挂,既然过了就没必要用输入外挂了,麻烦
#include<iostream>
#include<cstring>#include<queue>
using namespace std;
int A,B,C,T;
int map[55][55][55];
bool visited[55][55][55];
int d[6][3]={{0,1,0},{0,-1,0},{0,0,1},{0,0,-1},{1,0,0},{-1,0,0}};
struct node{
int x,y,z,time;
};
void bfs(){
queue<node>q;
node current,temp;
temp.x=temp.y=temp.z=temp.time=0;
q.push(temp);
visited[temp.x][temp.y][temp.z]=true;
while(!q.empty()){
current=q.front();
q.pop();
for(int i=0;i<6;i++){
int x=current.x+d[i][0];
int y=current.y+d[i][1];
int z=current.z+d[i][2];
if(!visited[x][y][z] && x>=0 && x<A && y>=0 && y<B && z>=0 && z<C && map[x][y][z]==0){
visited[x][y][z]=true;
temp.x=x;
temp.y=y;
temp.z=z;
temp.time=current.time+1;
if(temp.time>T){
cout<<-1<<endl;
return ;
}
else if(temp.x==A-1 && temp.y==B-1 && temp.z==C-1){
cout<<temp.time<<endl;
return ;
}
q.push(temp);
}
}
}
cout<<-1<<endl;
}
int main(){
int K;
scanf("%d",&K);
while(K--){
scanf("%d%d%d%d",&A,&B,&C,&T);
for(int i=0;i<A;i++)
for(int j=0;j<B;j++)
for(int k=0;k<C;k++)
scanf("%d",&map[i][j][k]);
if(map[A-1][B-1][C-1]==1){ //
cout<<-1<<endl;
continue;
}
if(A+B+C-3>T){ //最短路径大于时间T
cout<<-1<<endl;
continue;
}
memset(visited,false,sizeof(visited));
bfs();
}
return 0;
}