先贴个题目:
以及原题链接: 1096. 地牢大师 - AcWing题库https://www.acwing.com/problem/content/1098/
这题其实就是AcWing 1101. 献给阿尔吉侬的花束 解题思路及代码-CSDN博客这题的二维变三维,甚至没有啥难点,秒了。
代码如下:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 110;
int l, r, c;
int dx[6] = {0, 0, 0, 0, 1, -1}, dy[6] = {0, 0, 1, -1, 0, 0}, dz[6] = {1, -1, 0, 0, 0, 0};
char map[N][N][N];
int dis[N][N][N];
struct Point
{
int x, y, z;
};
bool operator==(Point &x, Point &y)
{
if (x.x == y.x && x.y == y.y && x.z == y.z)
return true;
else
return false;
}
int bfs(Point start, Point end)
{
dis[start.x][start.y][start.z] = 0;
queue<Point> q;
q.push(start);
while (q.size())
{
Point tmp = q.front();
q.pop();
if (tmp == end)
return dis[end.x][end.y][end.z];
for (int i = 0; i < 6; ++i)
{
int tx = tmp.x + dx[i];
int ty = tmp.y + dy[i];
int tz = tmp.z + dz[i];
if (tx < 0 || tx >= l || ty < 0 || ty >= r || tz < 0 || tz >= c)
continue;
if (dis[tx][ty][tz] == -1 && map[tx][ty][tz] != '#')
{
dis[tx][ty][tz] = dis[tmp.x][tmp.y][tmp.z] + 1;
Point ts;
ts.x = tx;
ts.y = ty;
ts.z = tz;
q.push(ts);
}
}
}
return -1;
}
int main()
{
while (1)
{
cin >> l >> r >> c;
if (!l || !r || !c)
break;
memset(dis, -1, sizeof(dis));
for (int i = 0; i < l; ++i)
{
getchar();
for (int j = 0; j < r; ++j)
scanf("%s", &map[i][j]);
}
Point start, end;
for (int i = 0; i < l; ++i)
{
for (int j = 0; j < r; ++j)
{
for (int k = 0; k < c; ++k)
{
if (map[i][j][k] == 'S')
{
start.x = i;
start.y = j;
start.z = k;
}
if (map[i][j][k] == 'E')
{
end.x = i;
end.y = j;
end.z = k;
}
}
}
}
int ans = bfs(start, end);
if (ans != -1)
printf("Escaped in %d minute(s).\n", ans);
else
printf("Trapped!\n");
}
return 0;
}
by————2024.4.6刷题记录