# 7576번 문제
# 1은 익은 토마토 0은 익지않은 토마토
N,M = map(int,input().split())
tomatoarray = [list(map(int,input().split())) for _ in range(M)]
dx = [-1,1,0,0]
dy = [0,0,1,-1]
tomatocnt = 0
total = N*M
tomato = []
for x in range(M):
for y in range(N):
if tomatoarray[x][y] == 1:
tomato.append((x,y))
tomatocnt += 1
elif tomatoarray[x][y] == -1:
total -= 1
result = -1
day = 0
if total == tomatocnt:
result = 0
else:
while tomato:
new_tomato = []
for x,y in tomato:
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx<M and 0<=ny<N:
if not tomatoarray[nx][ny]:
tomatoarray[nx][ny] = 1
new_tomato.append((nx,ny))
tomatocnt += 1
day += 1
if tomatocnt == total:
result = day
break
if len(new_tomato):
tomato = [row[:] for row in new_tomato]
else:
result = -1
break
print(result)
BFS를 활용해 day별로 새로 토마토가 된 곳을 찾아서 해주었다.
'알고리즘 > 백준' 카테고리의 다른 글
[BOJ/백준] 1062 가르침 (0) | 2021.05.02 |
---|---|
[BOJ/백준] 1976 여행 가자 (0) | 2021.04.08 |
[BOJ/백준] 2812 크게 만들기 (0) | 2021.04.08 |
[BOJ/백준] 14002 가장 긴 증가하는 부분 수열 4 (0) | 2021.04.08 |
[BOJ/백준] 16235 나무 재테크 (0) | 2021.04.08 |