https://www.acmicpc.net/problem/7576
import sys
from collections import deque
input = sys.stdin.readline
m, n = map(int, input().rstrip().split())
graph = [list(map(int, input().rstrip().split())) for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
q = deque()
def bfs():
while q:
a, b = q.popleft()
for i in range(4):
nx = dx[i] + a
ny = dy[i] + b
if 0<= nx < n and 0 <= ny < m:
if graph[nx][ny] == 0:
graph[nx][ny] = graph[a][b] + 1
q.append((nx, ny))
for i in range(n):
for j in range(m):
if graph[i][j] == 1: # 큐에 넣을 시작점 먼저 구하기
q.append((i, j))
bfs()
result = -2
flag = 0
for i in range(n):
for j in range(m):
if graph[i][j] == 0:
flag = 1 # flag = 1이면 덜 익은 토마토가 있는 것
else:
result = max(result, graph[i][j])
if flag == 1: # 덜 익은 토마토 존재
print(-1)
elif result == 1: # 처음부터 모두 익었을 때
print(0)
else:
print(result - 1)
처음에 모든 좌표를 돌면서 graph[i][j]가 1인 지점에서 bfs를 돌렸다가 예제 입력 3에서 오류가 발생했다. 모든 좌표를 돌면서 graph[i][j]가 1인 지점을 큐에 넣는 방법으로 해결했다.