Description
Input
Output
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
#include<stdio.h> #include<queue> #include<cstring> using namespace std; int visit[55][55][55]; int map[55][55][55]; int dir[6][3]={{0,0,1},{0,1,0},{1,0,0},{0,0,-1},{0,-1,0},{-1,0,0}}; struct node{ int x,y,z,s;}; int a,b,c; int abs(int w) { return w<0?-w:w; } int check(int x,int y,int z) { if(x>=0&&y>=0&&x<a&&y<b&&z>=0&&z<c&&map[x][y][z]==0) return 1; return 0; } int bfs(int m) { queue<node>q; node t,next; t.x=0; t.y=0; t.z=0; t.s=0; q.push(t); map[t.x][t.y][t.z]=1; while(!q.empty()) { t=q.front(); q.pop(); if(t.s>m) return -1; if(t.x==a-1&&t.y==b-1&&t.z==c-1&&t.s<=m) return t.s; for(int i=0;i<6;i++) { next.x=t.x+dir[i][0]; next.y=t.y+dir[i][1]; next.z=t.z+dir[i][2]; if(check(next.x,next.y,next.z)&&!visit[next.x][next.y][next.z]) { visit[next.x][next.y][next.z]=1; next.s=t.s+1; if(abs(next.x-a+1)+abs(next.y-b+1)+abs(next.z-c+1)+next.s>m) continue; q.push(next); } } } return -1; } int main() { int n,m; scanf("%d",&n); while(n--) { memset(map,0,sizeof(map)); memset(visit,0,sizeof(visit)); scanf("%d%d%d%d",&a,&b,&c,&m); 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]); int z=bfs(m); printf("%d\n",z); } }