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
11
解决方法二:main函数优化一下,判断c+x+y-3>time
代码:
#include <cstdio> #include <iostream> #include <queue> #include <algorithm> #include <cstring> using namespace std; struct node { int c,x,y,step; }; int T,c,n,m,time; int map[60][60][60],vis[60][60][60]; int fx[6][3]={1,0,0,0,1,0,0,0,1,-1,0,0,0,-1,0,0,0,-1}; int check(node p) { if(p.c<0||p.x<0||p.y<0||p.c>=c||p.x>=n||p.y>=m)return 0; if(vis[p.c][p.x][p.y])return 0; if(p.step>time)return 0; if(map[p.c][p.x][p.y])return 0; return 1; } int bfs() { queue<node>Q; node p,t; t.c=t.x=t.y=t.step=0; Q.push(t); vis[0][0][0]=1; while(!Q.empty()) { t=Q.front(); Q.pop(); if(t.c==c-1&&t.x==n-1&&t.y==m-1)return t.step; for(int i=0;i<6;i++) { p.c=t.c+fx[i][0]; p.x=t.x+fx[i][1]; p.y=t.y+fx[i][2]; p.step=t.step+1; /* if(p.c<0||p.x<0||p.y<0||p.c>=c||p.x>=n||p.y>=m)continue; if(vis[p.c][p.x][p.y])continue; if(p.step>time)continue; if(map[p.c][p.x][p.y])continue; Q.push(p); vis[p.c][p.x][p.y]=1; */ if(check(p)) { Q.push(p); vis[p.c][p.x][p.y]=1; } } } return -1; } int main() { scanf("%d",&T); while(T--) { memset(vis,0,sizeof(vis)); scanf("%d%d%d%d",&c,&n,&m,&time); for(int i=0;i<c;i++) for(int j=0;j<n;j++) for(int z=0;z<m;z++) scanf("%d",&map[i][j][z]); if(map[c-1][n-1][m-1]) printf("-1\n"); else if(c+n+m-3>time) printf("-1\n"); else printf("%d\n",bfs()); } return 0; }