一开始上来就BFS,交了好几次都超时,无奈网搜了一下别人AC了的博客,原来要特判一下,真是迟钝呢,不过提交的过程中竟然发现不同的编译器效果有这么大的差距,下图中代码大小差距只是第二次交的时候删掉了一个头文件而已,真是给跪了
#include <cstdio>
#include <queue>
using namespace std;
const short MAX = 50;
const short MOVE[6][3] = {
{1, 0, 0}, {-1, 0, 0},
{0, 1, 0}, {0, -1, 0},
{0, 0, 1}, {0, 0, -1}
};
struct Point{
short x, y, z;
};
short A, B, C, T; //3D edge length and time
short map[MAX][MAX][MAX];//map
inline bool isUnreachable(short x, short y, short z)
{
return x < 0 || x >= A ||
y < 0 || y >= B ||
z < 0 || z >= C ||
map[x][y][z] ;
}
short bfs()
{
//if dest is blocked or distance is already more than time given
if(map[A-1][B-1][C-1] || A + B + C - 3 > T) return -1;
//if dest is start
if(A == 1 && B == 1 && C == 1) return 0;
//step 1: initialize
Point now = {0, 0, 0}, nex;
queue<Point> q;
q.push(now);
map[0][0][0] = 1;//set visited blocked
//step 2: T level BFS
for(short t = 0; t < T && !q.empty(); ++t){
for(short n = q.size(); n > 0; --n){
now = q.front();
q.pop();
for(short i = 0; i < 6; ++i){
nex.x = now.x + MOVE[i][0];
nex.y = now.y + MOVE[i][1];
nex.z = now.z + MOVE[i][2];
if(isUnreachable(nex.x, nex.y, nex.z)) continue;
if(nex.x + 1 == A && nex.y + 1 == B && nex.z + 1 == C) return t + 1;
q.push(nex);
map[nex.x][nex.y][nex.z] = 1;//set visited blocked
}
}
}
return -1;
}
int main()
{
short test;
for(scanf("%d", &test); test > 0; --test){
//input map
scanf("%d %d %d %d", &A, &B, &C, &T);
for(short i = 0; i < A; ++i){
for(short j = 0; j < B; ++j){
for(short k = 0; k < C; ++k) scanf("%d", &map[i][j][k]);
}
}
//check if can get out
printf("%d\n", bfs());
}
return 0;
}