题目大意:给定一个三维的空间,还有起点和终点坐标,要你求到终点的最短距离
解题思路:最短距离用宽度优先遍历,分别考虑上下,左右,前后6个方向。题目很简单,就是要注意下坐标顺序
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct Point
{
int x, y, z;
};
struct node
{
Point pos;
int step;
};
const int maxn = 10;
int n;
Point start, end;
Point dir[6] = {{0,0, 1}, {0, 0, -1}, {0, -1, 0}, {0, 1, 0}, {1, 0, 0}, {-1, 0, 0}};
char data[maxn][maxn][maxn];
int bfs();
int main()
{
char s[10];
while(scanf("%s %d", s, &n) != EOF)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
scanf("%s", &data[i][j]);
}
scanf("%d %d %d %d %d %d", &start.z, &start.y, &start.x, &end.z, &end.y, &end.x);
scanf("%s", s);
int ans = bfs();
if(ans == -1)
printf("NO ROUTE\n");
else
printf("%d %d\n", n, ans);
}
return 0;
}
int bfs()
{
queue<node> que;
node s;
s.pos = start;
s.step = 0;
que.push(s);
data[start.x][start.y][start.z] = 'X';
while(!que.empty())
{
node tmp = que.front();
que.pop();
if(tmp.pos.x == end.x && tmp.pos.y == end.y && tmp.pos.z == end.z)
return tmp.step;
for(int i = 0; i < 6; i++)
{
int dx = tmp.pos.x + dir[i].x;
int dy = tmp.pos.y + dir[i].y;
int dz = tmp.pos.z + dir[i].z;
if(dx >=0 && dx < n && dy >= 0 && dy < n && dz >= 0 && dz < n && data[dx][dy][dz] != 'X')
{
data[dx][dy][dz] = 'X';
node t;
t.pos.x = dx;
t.pos.y = dy;
t.pos.z = dz;
t.step = tmp.step + 1;
que.push(t);
}
}
}
return -1;
}