39 lines
929 B
Python
39 lines
929 B
Python
from collections import deque
|
|
import sys
|
|
|
|
input = sys.stdin.readline
|
|
|
|
M, N = map(int, input().split())
|
|
emptyCount = 0
|
|
tomatoCount = 0
|
|
visited = [[-1]*M for _ in range(N)]
|
|
q = deque()
|
|
|
|
for n in range(N) :
|
|
row = list(map(int, input().split()))
|
|
for m in range(M) :
|
|
tomato = row[m]
|
|
if tomato == 1 :
|
|
q.append((m,n))
|
|
visited[n][m] = 0
|
|
tomatoCount += 1
|
|
elif tomato == -1 :
|
|
visited[n][m] = -2
|
|
emptyCount += 1
|
|
|
|
dm = [1,-1,0,0]
|
|
dn = [0,0,1,-1]
|
|
dayMax = 0
|
|
|
|
while len(q):
|
|
cm, cn = q.popleft()
|
|
|
|
for i in range(4) :
|
|
nm, nn = cm + dm[i], cn + dn[i]
|
|
if 0 <= nm < M and 0 <= nn < N and visited[nn][nm] == -1 :
|
|
q.append((nm,nn))
|
|
tomatoCount += 1
|
|
visited[nn][nm] = visited[cn][cm] + 1
|
|
dayMax = max(dayMax, visited[nn][nm])
|
|
|
|
print(dayMax if tomatoCount + emptyCount == N*M else -1) |