思路
将普通的迷宫最短路推广到三维,数据量比较小,思路和步骤与二维迷宫求最短路一致。
不过在加一个坐标,对于这道题来说,需要注意的是坐标的表示方式,题中的坐标为列行层。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct point
{
int l, x, y, step;
point(int ll, int xx, int yy, int st)
:l(ll), x(xx), y(yy), step(st)
{
}
};
int n, maze[10][10][10];
// 起始和终点
int bx, by, bz;
int ex, ey, ez;
char op[15];
// 增量
int ud[] = {1, -1, 0, 0, 0, 0};
int lr[] = {0, 0, 1, 0, -1, 0};
int fb[] = {0, 0, 0, 1, 0, -1};
void input()
{
scanf("%d", &n);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
scanf("%s", op);
for(int k=0; k<n; k++)
{
if(op[k]=='O') maze[i][j][k] = 0;
else maze[i][j][k] = 1;
}
}
}
scanf("%d%d%d%d%d%d", &by, &bx, &bz, &ey, &ex, &ez);
scanf("%s", op);
}
bool judge(int l, int x, int y)
{
// 判越界和可行
if(maze[l][x][y]==1) return false;
if(l>=n||l<0) return false;
if(x>=n||x<0) return false;
if(y>=n||y<0) return false;
return true;
}
void dfs()
{
queue<point> qu;
qu.push(point(bz, bx, by, 0));
while(!qu.empty())
{
point& tmp = qu.front();
int cur[] = {tmp.l, tmp.x, tmp.y, tmp.step};
if(cur[0]==ez&&cur[1]==ex&&cur[2]==ey)
{
printf("%d %d\n", n, cur[3]);
return;
}
else
{
qu.pop();
for(int i=0; i<6; i++)
{
int l = cur[0]+ud[i];
int x = cur[1]+fb[i];
int y = cur[2]+lr[i];
if(judge(l, x, y))
{
maze[l][x][y] = 1;
qu.push(point(l, x, y, cur[3]+1));
}
}
}
}
printf("NO ROUTE\n");
}
int main()
{
while(scanf("%s", op)!=EOF)
{
input();
dfs();
}
return 0;
}