思路
广搜,求最短路。这道题的数据让我有点无语,应该是路径相对来说比较单一。不需要指导函数来优化方向,用了优先队列和估价函数反而超时了(可能是浪费在各种操作和函数传递上面了吧,也有可能是我写题的方式不对)。
用普通的队列,再把各种函数调用也降到最低,才勉强过了。
代码
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const int maxn = 55;
bool maze[maxn][maxn][maxn];
int le, n, m, lim;
int ll[] = {1, 0, 0, 0, 0, -1};
int xx[] = {0, 1, 0, -1, 0, 0};
int yy[] = {0, 0, 1, 0, -1, 0};
struct point
{
int l, x, y, time;
// int f;
point(int _l, int _x, int _y, int _time)
:l(_l), x(_x), y(_y), time(_time)
{
// f = time + abs(le-l) + abs(n-x) + abs(m-y);
}
};
//struct cmp
//{
// bool operator()(const point& a, const point& b)
// {
// return a.f > b.f;
// }
//};
void input()
{
int tmp;
scanf("%d%d%d%d", &le, &n, &m, &lim);
for(int i=0; i<le; i++)
{
for(int j=0; j<n; j++)
{
for(int k=0; k<m; k++)
{
scanf("%d", &tmp);
maze[i][j][k] = tmp;
}
}
}
}
//bool judge(int l, int x, int y, int time)
//{
// if(time>lim) return false;
// if(maze[l][x][y]) return false;
// if(l<0||l>=le) return false;
// if(x<0||x>=n) return false;
// if(y<0||y>=m) return false;
// maze[l][x][y] = true;
// return true;
//}
void bfs()
{
// priority_queue<point, vector<point>, cmp> qu;
queue<point> qu;
qu.push(point(0, 0, 0, 0));
int l, x, y, time;
int curl, curx, cury;
while(!qu.empty())
{
// curl = qu.top().l;
// curx = qu.top().x;
// cury = qu.top().y;
// time = qu.top().time;
curl = qu.front().l;
curx = qu.front().x;
cury = qu.front().y;
time = qu.front().time;
qu.pop();
if((curl+1==le)&&(curx+1==n)&&(cury+1==m))
{
printf("%d\n", time);
return;
}
for(int i=0; i<6; i++)
{
l = curl+ll[i];
x = curx+xx[i];
y = cury+yy[i];
if(time+1>lim) continue;
if(l<0||l>=le) continue;
if(x<0||x>=n) continue;
if(y<0||y>=m) continue;
if(maze[l][x][y]) continue;
maze[l][x][y] = true;
qu.push(point(l, x, y, time+1));
}
}
printf("-1\n");
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
input();
bfs();
}
return 0;
}