#include<bits/stdc++.h>
#define X first
#define Y second
using namespace std;
int board[1002][1002];
int visited[1002][1002];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,-1,1 };
int main() {
int n, m;
queue<pair<int, int>> Q;
cin >> m >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> board[i][j];
if (board[i][j] == 1)Q.push({ i,j });
if (board[i][j] == 0)visited[i][j] = -1;
}
}
while (!Q.empty()) {
auto cur = Q.front(); Q.pop();
for (int i = 0; i < 4; i++) {
int nx = cur.X + dx[i];
int ny = cur.Y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= m)continue;
if ( visited[nx][ny] >= 0)continue;
visited[nx][ny] = visited[cur.X][cur.Y] + 1;
Q.push({ nx,ny });
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (visited[i][j] == -1) {
cout << -1;
return 0;
}
ans = max(ans, visited[i][j]);
}
}
cout << ans;
}