해당 문제는 최소 일자를 구해야 하므로
BFS(너비 우선 탐색)을 사용하여 풀이하는 문제이다.
7576번(https://www.acmicpc.net/problem/7576)
과 풀이법이 거의 유사하다. 2차원 배열과 3차원 배열이라는 차이정도만 있다.
코드는 다음과 같다
from collections import deque
M, N, H = map(int, input().split())
graph = [[list(map(int, input().split())) for _ in range(N)] for _ in range(H)]
dx = [0, 0, 1, -1, 0, 0]
dy = [1, -1, 0, 0, 0, 0]
dz = [0, 0, 0, 0, 1, -1]
queue = deque()
# M = 가로, N = 세로, H = 높이
# 1은 익은 토마토, 0은 익지 않은 토마토, -1은 토마토가 들어있지 않은 칸
# 값이 1인 3차원 배열 위치를 저장해 BFS로 탐색
def BFS():
while queue:
z, x, y = queue.popleft()
for i in range(6):
nx, ny, nz = x + dx[i], y + dy[i], z + dz[i]
if 0 <= nx < N and 0 <= ny < M and 0 <= nz < H: # 위치가 정상범주 안일때
if graph[nz][nx][ny] == 0: # 익지 않은 토마토라면
graph[nz][nx][ny] = graph[z][x][y] + 1
queue.append((nz, nx, ny))
for i in range(H):
for j in range(N):
for k in range(M):
if graph[i][j][k] == 1:
queue.append((i, j, k))
BFS()
notAbleToRipen = False
day_cnt = 0
for i in range(H):
for j in range(N):
for k in range(M):
if graph[i][j][k] == 0:
notAbleToRipen = True
day_cnt = max(day_cnt, graph[i][j][k])
if notAbleToRipen:
print(-1)
else:
print(day_cnt - 1)