미로찾기와 비슷하게 BFS 사용
다른점: 시작점이 하나가 아닌 여러개 가능
from collections import deque
m, n = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
visited= [[False] * m for _ in range(n)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
def tomato_bfs(graph, visited):
queue = deque()
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
queue.append((i, j))
visited[i][j] = True
while queue:
pop_x, pop_y = queue.popleft()
for i in range(4):
next_x = pop_x + dx[i]
next_y = pop_y + dy[i]
if next_x <= -1 or next_x >= n or next_y <= -1 or next_y >= m:
continue
if visited[next_x][next_y] != True and graph[next_x][next_y] == 0:
queue.append((next_x,next_y))
visited[next_x][next_y] = True
graph[next_x][next_y] = graph[pop_x][pop_y] + 1
tomato_bfs(graph,visited)
graph_max = max(map(max, graph))
print(-1) if any(0 in i for i in graph) else print(graph_max-1)
2차원 배열 원소 포함 판단하기
#list에 0이 존재
if all(0 not in n for n in list):
return True
#list에 0이 하나라도 존재
if any(0 in n for n in list):
return True
2차원 배열에서 max, min 값 찾기
map을 이용
#Max
max_value = max(map(max, list))
#Min
min_value = min(map(min, list))