之前一直排错出不来,忘了在check函数里面判断该点是否已经走过了;
很套路的BFS,直接套模板就好了;
特别的这里需要两个结构体,将p存进q计算后,把q弹出来;
#include <stdio.h> #include <string.h> #include <queue> #include <iostream> using namespace std ; const int N = 60; int map[N][N][N]; int vis[N][N][N]; int nx[] = {1,-1,0,0,0,0}; int ny[] = {0,0,1,-1,0,0}; int nz[] = {0,0,0,0,1,-1}; int a , b , c ,ans,t; struct node{ int x ; int y ; int z ; int step; }; int abs(int x) { if(x<0) return -x; else return x; } bool check(int i , int j , int k) { if(i<0||j<0||k<0||i>=a||j>=b||k>=c||map[i][j][k]==1) { return false; } return true; } int bfs(int x , int y , int z) { int i ; queue<node>Q; node p ,q; p.x=x; p.y=y; p.z=z; p.step=0; vis[x][y][z]=1; Q.push(p); while(!Q.empty()) { p=Q.front(); Q.pop(); if(p.x==a-1&&p.y==b-1&&p.z==c-1&&p.step<=t) { return p.step; } for(i=0;i<6;i++) { q=p; q.x+=nx[i]; q.y+=ny[i]; q.z+=nz[i]; if(!vis[q.x][q.y][q.z]&&check(q.x,q.y,q.z)) { q.step++; vis[q.x][q.y][q.z]=1; Q.push(q); } } } return -1; } int main() { int ncase; cin>>ncase; while(ncase--) { memset(map,0,sizeof(map)); memset(vis,0,sizeof(vis)); int i , j , k ; cin>>a>>b>>c>>t; for(i=0;i<a;i++) for(j=0;j<b;j++) for(k=0;k<c;k++) { scanf("%d",&map[i][j][k]); } ans=bfs(0,0,0); cout<<ans<<endl; } return 0 ; }
套路就是这样了,