#include <iostream>
#include <string.h>
using namespace std;
#define MAX 301
const int dy[4] = {-1, 1, 0, 0};
const int dx[4] = {0, 0, -1, 1};
int n, m;
int map[MAX][MAX];
int delMap[MAX][MAX];
bool check[MAX][MAX];
int totalLand, totalYear;
bool checkLand(){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(map[i][j]) return true;
}
}
return false;
}
void bfs(int y, int x){
for(int i = 0; i < 4; i++){
int ny = y + dy[i];
int nx = x + dx[i];
if(ny >= 0 && ny < n && nx >= 0 && nx < m){
if(map[ny][nx] == 0){
delMap[y][x]++;
}
}
}
}
void dfs(int y, int x){
for(int i = 0; i < 4; i++){
int ny = y + dy[i];
int nx = x + dx[i];
if(ny >= 0 && ny < n && nx >= 0 && nx < m){
if(map[ny][nx] && !check[ny][nx]){
check[ny][nx] = true;
dfs(ny, nx);
}
}
}
}
int main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> map[i][j];
}
}
while(1){
memset(delMap, 0, sizeof(delMap));
memset(check, 0, sizeof(check));
//check
totalLand = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(map[i][j] && check[i][j] == 0){
check[i][j] = true;
dfs(i, j);
totalLand++;
}
}
}
// 땅이 2개 거나 모든 땅이 0인 경우 break
if(totalLand >= 2){
break;
}else if(!checkLand()){
totalYear = 0;
break;
}
// bfs
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(map[i][j]){
bfs(i, j);
}
}
}
// melt
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
map[i][j] -= delMap[i][j];
if(map[i][j] < 0) map[i][j] = 0;
}
}
totalYear++;
}
cout << totalYear;
}