标签:
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<queue> #include<cmath> using namespace std; int a,b,c; char map[52][52][52]; char visit[52][52][52]; int to[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}; struct node { int x,y,z; int time; }; int go(int x,int y,int z) { if(x>=0&&x<a&&y>=0&&y<b&&z>=0&&z<c&&map[x][y][z]==0) return 1; return 0; } int bfs(int m) { queue<node> q; node st,ed; st.x=0; st.y=0; st.z=0; st.time=0; q.push(st); memset(visit,0,sizeof(visit)); visit[0][0][0]=1; while(!q.empty()) { st=q.front(); q.pop(); if(st.time>m) return -1; if(st.x==a-1&&st.y==b-1&&st.z==c-1&&st.time<=m) return st.time; for(int i=0;i<6;i++) { ed.x=st.x+to[i][0]; ed.y=st.y+to[i][1]; ed.z=st.z+to[i][2]; if(go(ed.x,ed.y,ed.z)&&visit[ed.x][ed.y][ed.z]==0) { visit[ed.x][ed.y][ed.z]=1; ed.time=st.time+1; if(abs(ed.x-a+1)+abs(ed.y-b+1)+abs(ed.z-c+1)+ed.time>m) continue; else q.push(ed); } } } return -1; } int main() { int t,ans,m; scanf("%d",&t); while(t--) { scanf("%d%d%d%d",&a,&b,&c,&m); memset(map,0,sizeof(map)); 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]); ans=bfs(m); printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/nefu929831238/p/5537275.html