풀이 방법 : BFS
3차원 배열이라는 것만 빼면 어느 BFS와 다를게 없는 문제
현재 위치에서 동서남북상하 6방향으로 이동할 수 있는지 체크하면서 목적지에 도달했을 경우 그 시간을 체크하면 된다.
#include <iostream>
#include <vector>
#include <queue>
#include <limits.h>
using namespace std;
struct Pos
{
int x = 0;
int y = 0;
int z = 0;
int Time = 0;
};
int DirX[6] = { 1,-1,0,0,0,0 };
int DirY[6] = { 0,0,1,-1,0,0 };
int DirZ[6] = { 0,0,0,0,1,-1 };
int main()
{
while (true)
{
int L, R, C;
cin >> L >> R >> C;
if (L == 0 && R == 0 && C == 0)
break;
bool check[31][31][31] = {};
char Building[31][31][31] = {};
int StartX = 0, StartY = 0, StartZ = 0;
int EndX = 0, EndY = 0, EndZ = 0;
for (int i = 0; i < L; ++i)
{
for (int j = 0; j < R; ++j)
{
for (int k = 0; k < C; ++k)
{
cin >> Building[i][j][k];
if (Building[i][j][k] == 'S')
{
StartX = k;
StartY = j;
StartZ = i;
}
else if (Building[i][j][k] == 'E')
{
EndX = k;
EndY = j;
EndZ = i;
}
}
}
}
Pos Start;
queue<Pos> pqPos;
Start.x = StartX;
Start.y = StartY;
Start.z = StartZ;
pqPos.push(Start);
bool Enable = false;
int MinTime = 0;
while (!pqPos.empty())
{
Pos TopPos = pqPos.front();
pqPos.pop();
if (TopPos.x == EndX &&
TopPos.y == EndY &&
TopPos.z == EndZ)
{
Enable = true;
MinTime = TopPos.Time;
break;
}
if (check[TopPos.z][TopPos.y][TopPos.x])
continue;
check[TopPos.z][TopPos.y][TopPos.x] = true;
for (int i = 0; i < 6; ++i)
{
Pos Next = TopPos;
Next.x += DirX[i];
Next.y += DirY[i];
Next.z += DirZ[i];
++Next.Time;
if (Next.x < 0 || Next.x >= C ||
Next.y < 0 || Next.y >= R ||
Next.z < 0 || Next.z >= L)
continue;
if (Building[Next.z][Next.y][Next.x] == '#')
continue;
pqPos.push(Next);
}
}
if (Enable)
cout << "Escaped in " << MinTime << " minute(s).\n";
else
cout << "Trapped!\n";
}
}