题目大意:
这道题就是一个简单的模板广搜,只不过是三维的,而且有一点剪枝而已。没有什么难度。
直接代码吧!
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <cstring>
#define N 55
//#define INF 1e9+7
using namespace std;
struct P{
int x,y,z,t;//多添加一个t表示时间,就可以减少内存的消耗,也可以达到剪枝的目的
};
P n;// 下一个点。
int map[N][N][N];
int t,x,y,z,steps;
//地图的6个方向。
int dre[6][3]={0,0,1,0,0,-1,1,0,0,-1,0,0,0,1,0,0,-1,0};
int bfs(){
// 在这里申请队列可以不用清空,我就是吃了这个亏
queue<P> que;
P p;
p.x = 0,p.y = 0,p.z = 0,p.t = 0;
que.push(p);
while(!que.empty()){
p = que.front();que.pop();
for (int i = 0;i < 6;i++){
n.x = p.x + dre[i][0];
n.y = p.y + dre[i][1];
n.z = p.z + dre[i][2];
n.t = p.t + 1;
// n.t <= steps 表示剪枝
if (0 <= n.x && n.x < x && 0 <= n.y && n.y < y && 0 <= n.z && n.z < z && map[n.x][n.y][n.z] == 0 && n.t <= steps){
if (n.x == x-1 && n.y == y-1 && n.z == z-1) {
return n.t;
}
P q;
q.x = n.x,q.y = n.y,q.z = n.z,q.t = n.t;
que.push(q);
map[q.x][q.y][q.z] = 1;
}
}
}
return -1;
}
int main(){
cin >> t;
while(t--){
//que.clear();
memset(map,0,sizeof(map));
cin >> x >> y >> z >> steps;
for (int i = 0;i < x;i++){
for (int j = 0;j < y;j++){
for (int k = 0;k < z;k++){
scanf("%d",&map[i][j][k]);
}
}
}
int ans = bfs();
//ans > steps ? -1:ans;
printf("%d\n",ans);
}
return 0;
}