题意:
BFS的小小变形,场景由二维迷宫变成三维空间的迷宫,基本框架是不变的.
这个题目就是考耐心嘛,毕竟就像一篇阅读理解,只需要看懂那个slice就是指z轴上不同点的平面就可以了.另外,需要注意题目中给出的起点的顺序是:start_y(列), start_x(行), start_z,这个需要跟自己的数组中的每一维的意义对应起来,否则结果就会不对.然后还要注意,每走到一个点,都会有6个方向的点(上\下\左\右\前\后)待探索.
代码:
// 0ms, 1804K
// BFS on a cubic maze
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct Location {
int x, y, z, step;
Location(int x, int y, int z, int s) : x(x), y(y), z(z), step(s) {
}
};
const int FAIL_VALUE = -1;
const int DIR[6][3] = { {1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1} }; // 6 directions every exploration
const int MAX_DIMEN(11);
char maze[MAX_DIMEN][MAX_DIMEN][MAX_DIMEN];
bool isVisited[MAX_DIMEN][MAX_DIMEN][MAX_DIMEN];
int dimen;
int _x2, _y2, _z2; // coordinates of target point
int _x1, __y1, _z1; // coordinates of start point
bool isValid(const int& x, const int& y, const int& z) {
return x >= 0 && y >= 0 && z >= 0 &&
x < dimen && y < dimen && z < dimen;
}
int bfs() {
memset(isVisited, false, sizeof isVisited); // initial visit-array
queue<Location> locations;
isVisited[_x1][__y1][_z1] = true;
locations.push( Location(_x1, __y1, _z1, 0) );
while (!locations.empty()) {
Location cur = locations.front();
//cout << _debug << "\t" << cur.step << endl;
locations.pop();
if (cur.x == _x2 && cur.y == _y2 && cur.z == _z2) { // if arriving at the target point
return cur.step;
}
for (int dir = 0; dir < 6; ++dir) {
int xx = cur.x + DIR[dir][0];
int yy = cur.y + DIR[dir][1];
int zz = cur.z + DIR[dir][2];
if (isValid(xx, yy, zz) && !isVisited[zz][xx][yy] && maze[zz][xx][yy] == 'O') { // those which can reach
isVisited[zz][xx][yy] = true;
locations.push( Location(xx, yy, zz, cur.step + 1) );
}
}
}
return FAIL_VALUE;
}
int main() {
// freopen("in.txt", "r", stdin);
char op[10];
while (cin >> op >> dimen) { // 'START N'
/* input phase */
int x, y, z;
for (int z = 0; z < dimen; ++z) {
for (int x = 0; x < dimen; ++x) {
for (int y = 0; y < dimen; ++y) {
cin >> maze[z][x][y];
}
}
}
cin >> __y1 >> _x1 >> _z1; // mind the order of input...
cin >> _y2 >> _x2 >> _z2;
cin >> op; // 'END'
/* process phase */
int need_step = bfs();
if (need_step == FAIL_VALUE) {
cout << "NO ROUTE" << endl;
} else {
cout << dimen << " " << need_step << endl;
}
}
return 0;
}