이번 문제는 주어진 토마토들의 위치 정보인 table에서 원소값이 1인 원소가 상하좌우의 근접값이 -1이 아니면 하나씩 퍼져나가는 형식으로 진행되어 결국에 전체가 다 퍼질려면 얼마나 걸리는지 확인하는 문제이다.
우선 데이터를 입력받을 때, 원소값이 1인 원소들의 위치값(i,j)을 start_points 리스트에 저장하고 이 start_points 리스트를 시작 노드로 삼아 하나씩 근접값을 체크하고 진행하였다. 이 문제와 같은 경우에는 갈수 있는 원소값이 0이고 갈 수 없는 원소값이 -1임으로 특별히 새로운 visited 리스트를 작성하지 않았고 table에 값을 추가하는 형식으로 진행하였다.
from collections import deque
m,n = map(int,input().split())
table = []
start_points = []
for i in range(n):
line = list(map(int,input().split()))
table.append(line)
for j in range(m):
if table[i][j] ==1:
start_points.append([j,i])
def bfs(table,start_points,m,n):
need_visited,temp_table = deque(start_points),table.copy()
control = [[1,0],[-1,0],[0,-1],[0,1]]
while need_visited:
now_x,now_y = need_visited.popleft()
for i in range(4):
next_x,next_y = now_x+control[i][0],now_y+control[i][1]
if -1<next_x<m and -1<next_y<n:
if temp_table[next_y][next_x] == 0 :
need_visited.append([next_x,next_y])
temp_table[next_y][next_x] = temp_table[now_y][now_x]+1
for i in temp_table:
if 0 in i:
return -1
return max(max(x) for x in temp_table) -1
print(bfs(table,start_points,m,n))