m, n = map(int, input().split())
tomatoes = [list(map(int, input().split())) for _ in range(n)]

# 상하좌우
def ripe(i, j):
    if (j-1 >= 0) and tomatoes[i][j-1] == 0:
        tomatoes[i][j-1] = 1
    
    if (j+1 <= m-1) and tomatoes[i][j+1] == 0:
        tomatoes[i][j+1] = 1
        
    if (i-1 >= 0 ) and tomatoes[i-1][j] == 0:
        tomatoes[i-1][j] = 1
        
    if (i+1 <= n-1 ) and tomatoes[i+1][j] == 0:
        tomatoes[i+1][j] = 1

count = 0
prv = 0

while True:
    count += 1
    
    for i in range(n):
        for j in range(m):
            if tomatoes[i][j] == 1:
                ripe(i,j)

    riped = sum(row.count(1) for row in tomatoes)
    
    if riped == prv:
        break
    else:
        prv = riped
        
    if riped == n * m :
        break

print(count if prv == n * m else -1)


from collections import deque

m, n = map(int, input().split())
tomatoes = [list(map(int, input().split())) for _ in range(n)]

# 처음부터 익어있는 토마토 위치를 큐에 넣기
queue = deque()
for i in range(n):
   for j in range(m):
       if tomatoes[i][j] == 1:
           queue.append((i, j, 0))  # (행, 열, 날짜)

# BFS
max_day = 0
while queue:
   i, j, day = queue.popleft()
   max_day = max(max_day, day)
   
   # 상하좌우 확인
   directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
   for x, y in directions:
		   x, y = x + dx, y + dy
       if 0 <= x < n and 0 <= y < m and tomatoes[x][y] == 0:
           tomatoes[x][y] = 1
           queue.append((x, y, day + 1))

# 덜 익은 토마토 확인
if any(0 in row for row in tomatoes):
   print(-1)
else:
   print(max_day)