from collections import deque
n, m = map(int, input().split())
box = [list(map(int, input().split())) for _ in range(m)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
queue = deque()
for j in range(m):
for i in range(n):
if box[j][i] == 1:
queue.append((i, j, 0))
max_days = 0
while queue:
x, y, day = queue.popleft()
max_days = max(max_days, day)
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and box[ny][nx] == 0:
box[ny][nx] = 1
queue.append((nx, ny, day + 1))
for row in box:
if 0 in row:
print(-1)
break
else:
print(max_days)
PREVIOUS[백준] 색종이 만들기