http://acm.hdu.edu.cn/showproblem.php?pid=1253
第一次做做三维的,思路跟二维的没有区别。这道题目第一次出现Memory Limit Exceeded 这种问题,找了很长时间才发现应该是先判断在存入,可以省很多内存。
代码:
#include<iostream>
#include<queue>
using namespace std;
int s[51][51][51];
int vis[51][51][51];
int _move[6][3] = { { 0, 0, 1 }, { 0, 0, -1 }, { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, {0,-1,0} };
int a, b, c, t, ok;
struct box
{
int x, y, z,time;
};
int bian(int x, int y, int z){
if (x < 0 || x >= a || y < 0 || y >= b || z < 0 || z >= c) return 0;
return 1;
}
void bfs(){
queue<box> qu;
box now = { 0, 0, 0,0 }, temp;
qu.push(now);
while (qu.size()>0)
{
now = qu.front(); qu.pop();
if (now.x == a - 1 && now.y == b - 1 && now.z == c - 1 && now.time <=t)
{
ok = 1;
cout << now.time << endl;
return;
}
for (int i = 0; i < 6; i++){
temp.x = now.x + _move[i][0];
temp.y = now.y + _move[i][1];
temp.z = now.z + _move[i][2];
temp.time = now.time + 1;
if (!bian(temp.x,temp.y,temp.z)) continue;
if (!s[temp.x][temp.y][temp.z]&&temp.time<=t){
s[temp.x][temp.y][temp.z] = 1;
if (abs(temp.x - a + 1) + abs(temp.y - b + 1) + abs(temp.z - c + 1) + temp.time>t)
continue;
qu.push(temp);
}
}
}
}
int main(){
int T;
scanf("%d", &T);
while (T--)
{
ok = 0;
cin >> a >> b >> c >> t;
for (int i = 0; i < a; i++){
for (int j = 0; j < b; j++){
for (int k = 0; k < c; k++){
scanf("%d", &s[i][j][k]);
}
}
}
bfs();
if (!ok) cout << -1 << endl;
}
return 0;
}