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
#include <stdio.h> #include <queue> #include <string.h> #include <algorithm> using namespace std; int vis[52][52][52]; int map[52][52][52]; int dir[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}}; //三维的方向、 int k,n,m; int ans; struct node { int z1,x1,y1; int time; } ; bool check(int z1,int x1,int y1) { if(z1>=k ||z1<0 ||x1>=n ||x1<0 ||y1>=m ||y1<0 ||vis[z1][x1][y1] ||map[z1][x1][y1]==1) //各种不满足情况都排除 return 0; return 1; } int bfs() { int i; queue<node>q; node st,ed; st.x1=0; st.y1=0; st.z1=0; st.time=0; q.push(st); while(!q.empty()) { st=q.front(); q.pop(); if(st.x1==n-1 &&st.y1==m-1 &&st.z1==k-1) return st.time; //逃脱 for(i=0;i<6;i++) { ed.x1=st.x1+dir[i][2]; ed.y1=st.y1+dir[i][1]; ed.z1=st.z1+dir[i][0]; if(!check(ed.z1,ed.x1,ed.y1)) continue; ed.time=st.time+1; vis[ed.z1][ed.x1][ed.y1]=1; q.push(ed); } } return 0; } int main() { int t,Time; int z,x,y; scanf("%d",&t); while(t--) { memset(vis,0,sizeof(vis)); scanf("%d%d%d%d",&k,&n,&m,&Time); for(z=0;z<k;z++) for(x=0;x<n;x++) for(y=0;y<m;y++) scanf("%d",&map[z][x][y]); ans=0; vis[0][0][0]=1; int ans=bfs(); // printf("%d\n",ans); if(ans&&ans<=Time) //时间小于规定时间则成功 printf("%d\n",ans); else printf("-1\n"); // 否则失败 } return 0; }
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int vis[52][52][52]; int map[52][52][52]; int dir[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}}; int k,n,m; int z,x,y; int ans; bool check(int z1,int x1,int y1) { if(z1>=k ||z1<0 ||x1>=n ||x1<0 ||y1>=m ||y1<0 ||vis[z1][x1][y1] ||map[z1][x1][y1]==1) return 0; return 1; } void dfs(int z,int x,int y,int time) { int sz,sx,sy,i; if(z==k-1 &&x==n-1 &&y==m-1) { ans=time; return; } for(i=0;i<6;i++) { sz=z+dir[i][0]; sx=x+dir[i][2]; sy=y+dir[i][1]; if(!check(sz,sx,sy)) continue; vis[sz][sx][sy]=1; time+=1; dfs(sz,sx,sy,time); vis[sz][sx][sy]=0; } return; } int main() { int t,Time; scanf("%d",&t); while(t--) { memset(vis,0,sizeof(vis)); scanf("%d%d%d%d",&k,&n,&m,&Time); for(z=0;z<k;z++) for(x=0;x<n;x++) for(y=0;y<m;y++) scanf("%d",&map[z][x][y]); ans=0; vis[0][0][0]=1; dfs(0,0,0,0); //printf("%d\n",ans); if(ans&&ans<=Time) printf("%d\n",ans); else printf("-1\n"); } return 0; }
原文地址:http://blog.csdn.net/sky_miange/article/details/43770115