Skip to content

Commit ab39bc4

Browse files
committed
[BOJ] #7576. 토마토 / 골드5 / 60분 / 성공
1 parent fce46b1 commit ab39bc4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
# 1. 입력 처리
6+
M, N = map(int, input().split()) # 가로 칸 수, 세로 칸 수
7+
box = [list(map(int, input().split())) for _ in range(N)] # 토마토
8+
9+
# 2. 초기 설정
10+
queue = deque([]) # 큐
11+
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 방향벡터
12+
day = 0 # 정답이 담길 변수
13+
14+
# 3. 큐에 초기 익은 토마토 위치 저장
15+
for i in range(N):
16+
for j in range(M):
17+
if box[i][j] == 1:
18+
queue.append((i, j))
19+
20+
# 4. BFS 탐색
21+
while queue:
22+
# 처음 토마토 꺼내기
23+
x, y = queue.popleft()
24+
25+
# 처음 토마토의 인접한 토마토 찾기
26+
for dx, dy in directions:
27+
nx, ny = x + dx, y + dy
28+
29+
# 범위 내에 있고, 토마토가 익지 않은 경우
30+
if (0 <= nx < N and 0 <= ny < M) and (box[nx][ny] == 0):
31+
# 익히고 1 더해주며 횟수 세기
32+
# 여기서 나온 제일 큰 값이 정답이 된다.
33+
box[nx][ny] += box[x][y] + 1 # 일수 누적
34+
queue.append((nx, ny))
35+
36+
37+
# 5. 정답 구하기
38+
for row in box:
39+
for tomato in row:
40+
# 모두 탐색했지만 토마토가 모두 익지 않았다면 -1 출력
41+
if tomato == 0:
42+
print(-1)
43+
exit()
44+
45+
# 다 익혔다면 최댓값이 정답
46+
day = max(day, max(row))
47+
48+
# 6. 정답 출력
49+
print(day - 1) # 처음에 1로 익은 토마토를 표현했으니 1을 빼준다.

0 commit comments

Comments
 (0)