var n, m, c;

function investigate(p){
	var a = 0;
	var q = [];
	for(var i = -1; i <= 1; ++i){
		for(var j = -1; j <= 1; ++j){
			var x = p[0] + i;
			var y = p[1] + j;
			if(!(i == 0 && j == 0) && 0 <= x && x < n && 0 <= y && y < m){
				if(c[x][y] == '.'){
					++a;
				}
				else{
					q[q.length] = [x, y];
				}
			}
		}
	}
	return [a >= +c[p[0]][p[1]], q];
}

function main(){
	n = scan();
	m = scan();
	c = Array(n);
	rep(n, function(i){
		c[i] = scan("string").split('');
	});
	var p = [];
	rep(n, function(i){
		rep(m, function(j){
			p[p.length] = [i, j];
		});
	});
	var a = 0;
	while(p.length != 0){
		/*
		rep(n, function(i){
			print(c[i].join(''));
		});
		print('');
		*/

		var v = false;
		var q = [];
		var r = [];
		var cnt = 0;
		rep(p.length, function(i){
			r[r.length] = investigate(p[i]);
		});
		rep(p.length, function(i){
			if(r[i][0]){
				c[p[i][0]][p[i][1]] = '.';
				q.push.apply(q, r[i][1]);
				v = true;
			}
		});
		if(v){
			++a;
		}
		p = q.slice(0);
	}
	print(a);
}

function rep(n, func){
	for(var i = 0; i < n; ++i){
		func(i);
	}
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

var input = '';
var input_index = 0;

function scan(type){
	if(type === 'string'){
		return input[input_index++];
	}
	else{
		return +input[input_index++];
	}
}

function print(val){
	console.log(val);
}

process.stdin.on('data', function(chunk){
	input += chunk;
});
process.stdin.on('end', function(){
	input = input.split(/\s+/);
	main();
});