A Jelly
题目地址:
基本思路:
这题本质上就是一个最基础的BFS找迷宫最短路,只是扩展到了三维的情况,所以相对而言麻烦一点点,要在空间里把每个位置想清楚。注意这种找最短路的最好用BFS写,开的一个dp数组在BFS过程中更新dp数组里每个位置的最小值。
参考代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define ll long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f
inline int read() {
int x = 0, neg = 1; char op = getchar();
while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
return neg * x;
}
inline void print(int x) {
if (x < 0) { putchar('-'); x = -x; }
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
const int maxn = 110;
//三维里的6个方向;
int d[6][3] = {{1,0,0},{-1,0,0},{0,0,1},{0,0,-1},{0,1,0},{0,-1,0}};
int n;
char a[maxn][maxn][maxn];
bool check(int x){
return x >= 1 && x <= n;
}
struct Node{
int x,y,z;
};
int dp[maxn][maxn][maxn];
signed main() {
cin >> n;
rep(i, 1, n) {
rep(j, 1, n) {
rep(k, 1, n) {
cin >> a[i][j][k];
dp[i][j][k] = INF;
}
}
}
queue<Node> que;
dp[1][1][1] = 1;
que.push({1, 1, 1});
while (!que.empty()) {
int x = que.front().x, y = que.front().y, z = que.front().z;
que.pop();
for (int i = 0; i < 6; i++) {
int nx = x + d[i][0], ny = y + d[i][1], nz = z + d[i][2];
if (a[nx][ny][nz] != '*' && check(nx) && check(ny) && check(nz) && dp[nx][ny][nz] == INF) {
dp[nx][ny][nz] = min(dp[nx][ny][nz],dp[x][y][z] + 1);
que.push({nx, ny, nz});
}
}
}
if (dp[n][n][n] == INF) cout << -1 << '\n';
else cout << dp[n][n][n] << '\n';
return 0;
}
京公网安备 11010502036488号