토마토
풀이 계획
- BFS
- 전체 리스트 순회하며 최외각 토마토만 큐에 저장
- 날짜++ 하며 list의 값 변경
import sys
from collections import deque
input = sys.stdin.readline
M, N = map(int, input().split())
map_lst = []
queue = deque([])
for i in range(N):
map_lst.append(list(map(int, input().split())))
for j in range(M):
if map_lst[i][j] == 1:
queue.append([j, i, 0])
# 상 우 하 좌
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
def bfs():
days = 0
while queue:
v = queue.popleft()
x = v[0]
y = v[1]
days = v[2]
for idx in range(4):
nx = x + dx[idx]
ny = y + dy[idx]
if nx < 0 or ny < 0 or nx >= M or ny >= N or map_lst[ny][nx] != 0:
continue
map_lst[ny][nx] = 1
queue.append([nx, ny, days + 1])
if queue:
days = queue[-1][2]
for ix in range(N):
if 0 in map_lst[ix]:
return -1
return days
print(bfs())
- days를 while 전에 초기화 안해서 에러가 생김. UnboundLocalError, NameError
- 그리고 days 리턴을 이상한데서 해서 틀림