三维迷宫,简单BFS
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Point{
int x;
int y;
int z;
int steps;
}start,end; //起点与终点
int n; //层数
char ***space; //保存太空
queue<Point> q; //BFS队列
int move[6][3] = {{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}};
void Create(){
//初始化太空
space = new char**[n + 2];
int i,j,k;
for(i=0; i<n+2; i++){
space[i] = new char*[n + 2];
for(j=0; j<n+2; j++){
space[i][j] = new char[n + 2];
}
}
for(j=0; j<n+2; j++){
for(k=0; k<n+2; k++){
space[0][j][k] = space[n+1][j][k] = 'X';
}
}
for(i=1; i<=n; i++){
for(j=0; j<n+2; j++){
space[i][j][0] = space[i][j][n+1] = 'X';
}
for(k=0; k<n+2; k++){
space[i][0][k] = space[i][n+1][k] = 'X';
}
}
for(i=1; i<=n; i++){
for(j=1; j<=n; j++){
for(k=1; k<=n; k++){
cin>>space[i][j][k];
}
}
}
cin>>start.z>>start.y>>start.x;
cin>>end.z>>end.y>>end.x;
start.z++;start.y++;start.x++;start.steps = 0;
end.z++;end.y++;end.x++;
q.push(start);
}
int BFS(){
//最短路径
if(start.x == end.x && start.y == end.y && start.z == end.z)return 0;
while(!q.empty()){
start = q.front();
q.pop();
for(int i=0; i<6; i++){
Point temp;
temp.x = start.x + move[i][0];
temp.y = start.y + move[i][1];
temp.z = start.z + move[i][2];
temp.steps = start.steps + 1;
if(temp.x == end.x && temp.y == end.y && temp.z == end.z)return temp.steps;
if(space[temp.x][temp.y][temp.z] == 'O'){
space[temp.x][temp.y][temp.z] = 'X';
q.push(temp);
}
}
}
return -1;
}
int main(){
string s; //输入
while(cin>>s>>n){
Create();
cin>>s;
int steps = BFS();
if(steps == -1)cout<<"NO ROUTE"<<endl;
else cout<<n<<' '<<steps<<endl;
while(!q.empty())q.pop();
}
return 0;
}