```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10000)
N,M = map(int, input().split())
maps = [[0 for _ in range(M)] for _ in range(N)]
queue = []
visited = [[-1 for _ in range(M)] for _ in range(N)]
# build map
for n in range(N):
row = list(map(int, input().split()))
for m in range(M):
maps[n][m] = row[m]
if row[m] == 1:
queue.append((n,m)) # put shark
max_dist = 0
while queue:
i,j = queue.pop(0)
if maps[i][j] == 1:
visited[i][j] = 0
for u,v in [(i+1,j+1), (i+1,j), (i+1,j-1), (i,j+1), (i,j-1), (i-1,j+1), (i-1,j), (i-1,j-1)]:
if (0 <= u < N) and (0 <= v < M):
if visited[u][v] == -1:
visited[u][v] = visited[i][j] + 1
max_dist = max(max_dist, visited[u][v])
queue.append((u,v))
print(max_dist)
```