Skip to content

Commit 88c9f7c

Browse files
committed
[BOJ] #7568. 토마토 (3차원) / 골드5 / 30분 / 성공
1 parent ab39bc4 commit 88c9f7c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
# 1. 입력 처리
6+
M, N, H = map(int, input().split()) # 가로, 세로, 높이
7+
box = [[list(map(int, input().split())) for _ in range(N)] for _ in range(H)]
8+
9+
# 2. 초기 변수 설정
10+
queue = deque([])
11+
directions = [(-1, 0, 0), (0, 1, 0), (1, 0, 0), (0, -1, 0),
12+
(0, 0, 1), (0, 0, -1)] # 위-오른쪽-아래-왼쪽-앞-뒤
13+
day = 0 # 정답으로 반환할 변수
14+
15+
# 3. 초기 익은 토마토를 큐에 추가하기
16+
for i in range(H):
17+
for j in range(N):
18+
for k in range(M):
19+
if box[i][j][k] == 1:
20+
queue.append((i, j, k))
21+
22+
# 4. BFS 탐색
23+
while queue:
24+
z, y, x = queue.popleft()
25+
26+
for dx, dy, dz in directions:
27+
nx, ny, nz = x + dx, y + dy, z + dz
28+
# 범위 내에 있고 아직 안 익은 토마토라면
29+
if (0 <= nx < M and 0 <= ny < N and 0 <= nz < H) and (box[nz][ny][nx] == 0):
30+
box[nz][ny][nx] += box[z][y][x] + 1 # 익은 날짜 누적 갱신
31+
queue.append((nz, ny, nx))
32+
33+
# 5. 정답 구하기
34+
for height in box:
35+
for row in height:
36+
for tomato in row:
37+
# 안 익은 토마토가 남아있는지 여부 확인
38+
if tomato == 0:
39+
print(-1)
40+
exit()
41+
# 익는데 걸린 최대 일수 추적
42+
day = max(day, max(row))
43+
44+
# 6. 정답 출력
45+
print(day - 1)

0 commit comments

Comments
 (0)