BFS模板题。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int x, y, z;
};
const int maxn = 100+1;
char ch[maxn][maxn][maxn];
int dis[maxn][maxn][maxn];
queue<Node> q;
//进行上下左右前后的移动
int mv[6][3] {
{0,0,1},
{0,0,-1},
{1,0,0},
{-1,0,0},
{0,1,0},
{0,-1,0}
};
int main() {
int n;
memset(dis, -1, sizeof(dis));
cin>>n;
for (int i=1;i<=n;i++) {
for (int j=1;j<=n;j++) {
for (int k=1;k<=n;k++) {
cin>>ch[i][j][k];
}
}
}
q.push({1,1,1});
dis[1][1][1] = 1;
int ans = INT_MAX;
int next_x, next_y, next_z;
while (q.size()) {
Node p = q.front();
q.pop();
for (int i=0;i<6;i++) {
next_x = p.x+mv[i][0];
next_y = p.y+mv[i][1];
next_z = p.z+mv[i][2];
if (next_x<=0||next_x>n||next_y<=0||next_y>n||next_z<=0||next_z>n||dis[next_x][next_y][next_z]!=-1) continue;
if (ch[next_x][next_y][next_z]=='.') {
dis[next_x][next_y][next_z] = dis[p.x][p.y][p.z]+1;
q.push({next_x, next_y, next_z});
}
}
}
cout<<dis[n][n][n];
return 0;
}

京公网安备 11010502036488号