https://www.acmicpc.net/problem/7576

창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
bfs를 사용하여 해결
import sys
from collections import deque
row, col = map(int, sys.stdin.readline().split())
graph = []
queue = deque()
for _ in range(col):
graph.append(list(map(int, sys.stdin.readline().strip().split())))
for y in range(col):
for x in range(row):
if graph[y][x] == 1:
queue.append((y, x))
while queue:
cur_y, cur_x = queue.popleft()
ny = [1, -1, 0, 0]
nx = [0, 0, 1, -1]
for i in range(4):
next_y = cur_y + ny[i]
next_x = cur_x + nx[i]
if 0 <= next_x < row and 0 <= next_y < col:
if graph[next_y][next_x] == 0:
graph[next_y][next_x] = graph[cur_y][cur_x] + 1
queue.append((next_y, next_x))
answer = 0
for box in graph:
for tomato in box:
if tomato == 0:
print(-1)
exit()
answer = max(answer, max(box))
print(answer - 1)