C語言源碼: [cpp] #include<stdio.h> int s[51][51][51]; int queue[500000][3]; int main() { int i,j,k,T,n,a,b,c,front,rear,num,flag; while(scanf("%d",&n)!=EOF) { while(n--) { scanf("%d %d %d %d",&a,&b,&c,&T); for(i=0;i<a;i++) for(j=0;j<b;j++) for(k=0;k<c;k++) scanf("%d",&s[i][j][k]); if(s[a-1][b-1][c-1]==1) { printf("-1\n"); continue; } s[0][0][0]=0; front=0; rear=0; num=0; flag=1; queue[0][0]=0; queue[0][1]=0; queue[0][2]=0; rear++; while(front!=rear) { i=queue[front][0]; j=queue[front][1]; k=queue[front][2]; front++; if(s[i][j][k]!=1) { s[i][j][k]=1; if(i==a-1&&j==b-1&&k==c-1) break; if(i>0&&s[i-1][j][k]==0) { queue[rear][0]=i-1; queue[rear][1]=j; queue[rear][2]=k; rear++; } if(i<a-1&&s[i+1][j][k]==0) { queue[rear][0]=i+1; queue[rear][1]=j; queue[rear][2]=k; rear++; } if(j>0&&s[i][j-1][k]==0) { queue[rear][0]=i; queue[rear][1]=j-1; queue[rear][2]=k; rear++; } if(j<b-1&&s[i][j+1][k]==0) { queue[rear][0]=i; queue[rear][1]=j+1; queue[rear][2]=k; rear++; } if(k>0&&s[i][j][k-1]==0) { queue[rear][0]=i; queue[rear][1]=j; queue[rear][2]=k-1; rear++; } if(k<c-1&&s[i][j][k+1]==0) { queue[rear][0]=i; queue[rear][1]=j; queue[rear][2]=k+1; rear++; } } if(front==flag) { flag=rear; num++; } } if(num<=T&&s[a-1][b-1][c-1]==1) printf("%d\n",num); else printf("-1\n"); } } }