Skip to content

Commit f93ad3e

Browse files
authored
feat: 5월 3주차 스터디 발제 파일 업로드
1 parent 77dbc25 commit f93ad3e

File tree

1 file changed

+54
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)