简单三维地图,直接广搜就行了。
#include<iostream>
#include<queue>
#include<string.h>
#include<stdio.h>
using namespace std;
int Map[55][55][55];
bool vis[55][55][55];
int f[6][3] = {{ -1, 0, 0}, {0, 1, 0}, {1, 0, 0}, {0, -1, 0}, {0, 0, -1}, {0, 0, 1}};
struct pos {
int x, y, z, step;
};
int BFS ( int a, int b, int c, int t ) {
pos temp;
temp.x = 0;
temp.y = 0;
temp.z = 0;
temp.step = 0;
queue<pos>Q;
Q.push ( temp );
while ( !Q.empty() ) {
pos tmp;
temp = Q.front();
if ( temp.x == a - 1 && temp.y == b - 1 && temp.z == c - 1 && temp.step <= t ) {
return temp.step;
}
for ( int i = 0; i < 6; i++ ) {
tmp.x = temp.x + f[i][0];
tmp.y = temp.y + f[i][1];
tmp.z = temp.z + f[i][2];
tmp.step = temp.step + 1;
if ( tmp.x >= 0 && tmp.x < a && tmp.y >= 0 && tmp.y < b && tmp.z >= 0 && tmp.z < c ) {
if ( Map[tmp.x][tmp.y][tmp.z] == 0 && !vis[tmp.x][tmp.y][tmp.z] ) {
Q.push ( tmp );
vis[tmp.x][tmp.y][tmp.z]=1;
}
}
}
Q.pop();
}
return -1;
}
int main() {
int K, A, B, C, T;
scanf ( "%d", &K );
while ( K-- ) {
scanf ( "%d%d%d%d", &A, &B, &C, &T );
memset ( vis, 0, sizeof ( vis ) );
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] );
}
}
}
if ( Map[A - 1][B - 1][C - 1] == 1 ) {
printf ( "-1\n" );
continue;
}
printf ( "%d\n", BFS ( A, B, C, T ) );
}
}