https://www.acmicpc.net/problem/7576
import sys
from collections import deque
input = sys.stdin.readline
m, n = map(int, input().split())
tomato = []
que = deque([])
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
tomato = [list(map(int, input().split()))for _ in range(n)]
for i in range(n):
for j in range(m):
if tomato[i][j] == 1:
que.append([i, j])
def bfs():
while que:
x, y = que.popleft()
for i in range(4):
nx = dx[i] + x
ny = dy[i] + y
if 0 <= nx < n and 0 <= ny < m and tomato[nx][ny] == 0:
tomato[nx][ny] = tomato[x][y] + 1
que.append([nx, ny])
bfs()
result = 0
for i in tomato:
for j in i:
if j == 0:
print(-1)
exit(0)
result = max(result, max(i))
print(result-1)
먼저 토마토(1) 의 위치를 알아놓은뒤, que에 저장한다.
이후 bfs를 이용해 풀면 된다.