less than 1 minute read

문제

접근 방법

그냥 3차원 배열에 bfs를 하는 문제였다.

정답 코드

import sys
from collections import deque

input = sys.stdin.readline

'''
그냥 3차원 bfs 같다..
'''

moves = [(0,0,1),(0,0,-1),(0,1,0),(0,-1,0),(1,0,0),(-1,0,0)]

def bfs(start_f, start_h, start_w):
  time = -1
  escape_time = [[[-1]*c for _ in range(r)] for _ in range(l)]
  escape_time[start_f][start_h][start_w] = 0

  q = deque([[start_f,start_h,start_w]])
  while q:
    f,h,w = q.popleft()
    if building[f][h][w]=='E':
      time = escape_time[f][h][w]
      break

    for df,dh,dw in moves:
      new_f, new_h, new_w = f+df, h+dh, w+dw
      if 0<=new_f<l and 0<=new_h<r and 0<=new_w<c and building[new_f][new_h][new_w] != '#' and escape_time[new_f][new_h][new_w] == -1:
        escape_time[new_f][new_h][new_w] = escape_time[f][h][w] + 1
        q.append([new_f, new_h, new_w])

  if time == -1:
    print("Trapped!")
  else:
    print(f"Escaped in {time} minute(s).")



while True:
  l,r,c = map(int, input().split())
  if l==0 and r==0 and c==0:
    break

  building = []
  
  for _ in range(l):
    build = []
    for _ in range(r):
      build.append(list(input().rstrip()))
    input().rstrip() #빈 줄 처리
    building.append(build)

  start_f,start_h,start_w = 0,0,0

  for i in range(l):
    for j in range(r):
      for k in range(c):
        if building[i][j][k] == 'S':
          bfs(i,j,k)