from collections import deque
# 입력
m,n=map(int,input().split())
tomato = [list(map(int,input().split())) for _ in range(n)]
queue = deque([])
dx = [-1,1,0,0]
dy = [0,0,-1,1]
# 처리
for i in range(n):
for j in range(m):
if tomato[i][j] == 1:
queue.append([i,j])
def ripe():
while queue:
x,y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx<n and 0<=ny<m and tomato[nx][ny] == 0:
tomato[nx][ny] = tomato[x][y] + 1
queue.append([nx,ny])
ripe()
for i in range(n):
for j in range(m):
if tomato[i][j] == 0:
print(-1)
exit(0)
print(max(map(max, tomato))-1)