题目[胜利大逃亡]:http://ac.jobdu.com/problem.php?pid=1456
坐标变换数组是一种很好的形式,以后多尝试
#include<cstdio>
#include<queue>
using namespace std;
int cas[51][51][51] = { 0 }; //坐标点
int mark[51][51][51] = { 0 }; //是否已访问
int a, b, c, t;
int go[][3] = { //坐标变换数组
1,0,0,
-1,0,0,
0,1,0,
0,-1,0,
0,0,1,
0,0,-1
};
struct point {
int x, y, z;//坐标
int time; //访问到本点的最短时间
};
queue<point> N; //队列
int BFS() {
while (!N.empty()) {//非空
point temp = N.front(); // 出队列
N.pop();
point now;
for (int i = 0; i < 6; i++) {
now.x = temp.x + go[i][0];
now.y = temp.y + go[i][1];
now.z = temp.z + go[i][2];
now.time = temp.time + 1;
if (now.x < 0 || now.x >= a || now.y < 0
|| now.y >= b || now.z < 0 || now.z >= c)//区域外
continue;
if (1 == mark[now.x][now.y][now.z]) continue; //已访问
if (1 == cas[now.x][now.y][now.z]) continue; //墙
N.push(now); //入队列
mark[now.x][now.y][now.z] = 1;
if (a - 1 == now.x && b - 1 == now.y
&& c - 1 == now.z)//到达终点
return now.time;
}
}
return -1;
}
int main() {
int n;
scanf("%d", &n);
while (n-- > 0) {
//初始化数据
scanf("%d%d%d%d", &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", &cas[i][j][k]);
mark[i][j][k] = 0;
}
while (N.empty() == false) N.pop(); //清队列
point temp;
temp.x = temp.y = temp.z = temp.time = 0;
N.push(temp); // 零点入队列
int BFS_minT = BFS();
if (BFS_minT <= t)
printf("%d\n", BFS_minT);
else
printf("-1\n");
}//while
return 0;
}