传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1253
思路:bfs三维模板题。存图之后,bfs(0,0,0), 然后就走能到达的点,标记,步数+1,然后判断即可。
比赛的时候怎么也写不出来,貌似边界弄错了(一直以为是存图的原因),后来写的时候还是不对!! check函数里面if有分号。。。。
通过题目发现了短板,结构体构造函数也忘了。。
AC代码:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <sstream>
#include <stack>
using namespace std;
#define mem(a,b) memset((a),(b),sizeof(a))
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF =0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1.0);
const double eps = 1e-5;
const ll mod = 1e9+7;
//head
int a[60][60][60];
bool vis[60][60][60];
int des[6][3] = {0, 1, 0, 1, 0, 0, 0, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 1};//6个方向
struct node{
int x, y, z;
int step;
node(){}
node(int _x, int _y, int _z, int _step):x(_x), y(_y), z(_z), step(_step){}
}temptop, f;
int _, n, m, l, t;
bool check(int x, int y, int z) {//该点是否满足
if(x < 0 || x >= n || y < 0 || y >= m || z < 0 || z >= l)
return false;
if(vis[x][y][z] || a[x][y][z])
return false;
return true;
}
int bfs(int x, int y, int z) {
queue<node> q;
q.push(node(x, y, z, 0));//起点入队
vis[x][y][z] = true;
while(!q.empty()) {
temptop = q.front();
q.pop();
if(temptop.x == n-1 && temptop.y == m-1 && temptop.z == l-1)//出口
return temptop.step;
for(int i = 0; i < 6; i++) {//bfs
int newx = temptop.x + des[i][0];
int newy = temptop.y + des[i][1];
int newz = temptop.z + des[i][2];
if(check(newx, newy, newz)) {//可以达到就步数+1,标记,入队
vis[newx][newy][newz] = true;
q.push(node(newx, newy, newz, temptop.step + 1));
}
}
}
return -1;//不能达到
}
int main() {
for(scanf("%d", &_);_;_--) {
mem(vis, false);
scanf("%d%d%d%d", &l, &n, &m ,&t);
for(int k = 0; k < l; k++) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
scanf("%d", &a[i][j][k]);
}
}
int ans = bfs(0, 0, 0);//起点
if(ans > t || ans == -1)//不满足的条件
printf("-1\n");
else
printf("%d\n", ans);
}
}