三维BFS,直接搬模板就好
#include <bits/stdc++.h> using namespace std; const int N = 110; int n; char m[N][N][N]; int dis[N][N][N]; typedef struct Edge { int third; int second; int first; }three; int bfs() { queue<three> q; memset(dis, -1, sizeof dis); q.push({1, 1, 1}); dis[1][1][1] = 1; int dx[] = {0, 1, 0, -1 ,0 , 0}, dy[] = {1, 0, -1, 0, 0, 0}, dz[] = {0, 0, 0, 0, 1, -1}; while(q.size()) { three t = q.front(); q.pop(); for(int i = 0; i < 6; i++) { int x = t.third + dx[i], y = t.second + dy[i], z = t.first + dz[i]; if(x >= 1 && y >= 1 && z >= 1 && x <= n && y <= n && z <= n && dis[x][y][z] == -1 && m[x][y][z] != '*') { dis[x][y][z] = dis[t.third][t.second][t.first] + 1; q.push({x, y, z}); } } } return dis[n][n][n]; } int main() { cin >> n; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) for(int k = 1; k <= n; k++) cin >> m[i][j][k]; auto t = bfs(); if(t == -1) cout << -1 << endl; else cout << t << endl; return 0; }