Skip to content

Commit 59806cf

Browse files
committed
[BOJ] #7569. 토마토 / 골드5 / 1시간 30분 / 실패
1 parent 1f19106 commit 59806cf

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import sys
2+
from collections import deque
3+
4+
input = sys.stdin.readline
5+
6+
# 상자의 가로 m, 세로 n, 높이 h
7+
m, n, h = map(int, input().split())
8+
tomatoes = []
9+
10+
for _ in range(h):
11+
layer = [list(map(int, input().split())) for _ in range(n)]
12+
tomatoes.append(layer)
13+
14+
15+
# 상하좌우앞뒤 방향
16+
directions = [(0, 0, 1), (0, 0, -1), (0, -1, 0), (0, 1, 0), (1, 0, 0), (-1, 0, 0)] # 상하좌우앞뒤
17+
18+
def bfs():
19+
queue = deque() # (층, 행, 열, 일수)
20+
21+
# 초기 익은 토마토 위치 큐에 추가
22+
for z in range(h):
23+
for x in range(n):
24+
for y in range(m):
25+
if tomatoes[z][x][y] == 1:
26+
queue.append((z, x, y, 0)) # (층, 행, 열, 일수)
27+
28+
max_day = 0 # 익는 데 걸린 최대 일수 추적
29+
30+
while queue:
31+
z, x, y, day = queue.popleft()
32+
max_day = max(max_day, day) # 가장 오래 걸린 일수 갱신
33+
34+
for dz, dx, dy in directions:
35+
nz, nx, ny = z + dz, x + dx, y + dy
36+
if 0 <= nz < h and 0 <= nx < n and 0 <= ny < m:
37+
if tomatoes[nz][nx][ny] == 0: # 익지 않은 토마토일 때
38+
tomatoes[nz][nx][ny] = 1
39+
queue.append((nz, nx, ny, day + 1)) # 익는 데 하루 추가
40+
41+
42+
return max_day
43+
44+
def all_ripe():
45+
# 모든 토마토가 익었는지 확인
46+
for i in range(h):
47+
for j in range(n):
48+
for k in range(m):
49+
if tomatoes[i][j][k] == 0:
50+
return False
51+
return True
52+
53+
# 초기 상태 확인
54+
if all_ripe():
55+
print(0)
56+
exit(0)
57+
else:
58+
days = bfs()
59+
60+
# 모든 토마토가 익었는지 다시 확인
61+
if all_ripe():
62+
print(days)
63+
else:
64+
print(-1)
65+

0 commit comments

Comments
 (0)