from collections import deque
import sys
input = sys.stdin.readline
def solve():
m, n = map(int, input().split())
farm = [[*map(int, input().split())] for _ in range(n)]
queue = deque()
dxy = [(-1, 0), (1, 0), (0, -1), (0, 1)]
answer = 0
for i in range(n):
for j in range(m):
if farm[i][j] == 1:
queue.append((i, j))
def bfs():
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dxy[i][0]
ny = y + dxy[i][1]
if 0 <= nx < n and 0 <= ny < m and farm[nx][ny] == 0:
farm[nx][ny] = farm[x][y] + 1
queue.append((nx, ny))
bfs()
for i in farm:
for j in i:
if j == 0:
print(-1)
exit()
answer = max(answer, max(i))
print(answer-1)
solve()