from collections import deque
w , h = map(int, input().split())
tomato = [list(map(int, input().split())) for _ in range(h)]
queue = deque()
for i in range(h):
for j in range(w):
if tomato[i][j] == 1: #값이1인지점부터 시작해야하니까 1인 지점들의 위치 기억
queue.append([i,j])
#상하좌우
di = [-1, 1, 0, 0]
dj = [0, 0, -1, 1]
def bfs():
while queue:
# 큐에 저장한 인덱스(익은애)를 기준으로 상, 하, 좌, 우 값 바꿔주기
i, j = queue.popleft()
# 상하좌우 좌표
# 주변의 값을 바꾸고(주변을 익히고)
for k in range(4):
ni = i + di[k]
nj = j + dj[k]
#범위 벗어나면 넘어가기
if ni < 0 or ni >= h or nj < 0 or nj >= w:
continue
#비어있으면 넘어가기
if tomato[ni][nj] == -1:
continue
if tomato[ni][nj] == 0:
tomato[ni][nj] = tomato[i][j] + 1
#주변이 이제 주인공이 되어 주변의 값을 바꿔주기 위해 인덱스 큐에 저장
#익은애가 이제 주인공이 되어 주변을 익히기 위해 보인 인덱스 저장
queue.append([ni,nj])
#안익은애 있으면 -1리턴
for a in range(h):
for b in range(w):
if tomato[a][b] == 0:
return -1
#토마토 리스트에서 가장 큰 값-1을 리턴
return max(map(max, tomato))-1
print(bfs())
큐에 저장한 인덱스(익은 토마토)를 기준으로 상, 하, 좌, 우 값을 검사해 익지 않았으면 익음처리해준다.
tomato = [list(map(int, input().split())) for _ in range(h)]
max(map(max, 리스트이름))
을 사용하면 된다.from collections import deque
w, h = map(int, input().split())
tomato = [list(map(int, input().split())) for _ in range(h)]
queue = deque()
for i in range(h):
for j in range(w):
#1이면 큐에 담아준다
if tomato[i][j] == 1:
queue.append([i,j])
dx = [-1,1,0,0]
dy = [0,0,-1,1]
def bfs():
#위에서 큐에 값을 담았으므로 바로 while문 진행
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x+dx[i]
ny = y+dy[i]
if 0<=nx<h and 0<=ny<w and tomato[nx][ny]==0:
tomato[nx][ny] = tomato[x][y]+1
queue.append([nx,ny])
day = 0
for i in range(h):
for j in range(w):
if tomato[i][j] == 0:
return -1
elif tomato[i][j] > day:
day = tomato[i][j]
return day-1
#처음부터 익어있었던 토마토박스는 최댓값이 1이므로 day는 0으로 리턴받는다.
print(bfs())