def change(i, j)
  $cnt[i][j] = 0
  (-1..1).each do |y|
    (-1..1).each do |x|
      next if x == 0 && y == 0 || i+y < 0 || i+y >= $h || j+x < 0 || j+x >= $w
      $cnt[i+y][j+x] += 1
    end
  end
end 
$h, $w = gets.split.map(&:to_i)
$fld = Array.new($h){ Array.new }
$h.times{ |i| $fld[i] = gets.chomp.gsub('.', '0').split('').map(&:to_i) }
$cnt = Array.new($h){ Array.new($w, 0) }
$h.times do |i|
  $w.times do |j|
    change(i, j) if $fld[i][j] == 0
  end
end
ret = 0
f = false
until f
  f = true
  arr = []
  (1...$h-1).each do |i|
    (1...$w-1).each do |j|
      if $fld[i][j] > 0 && $cnt[i][j] >= $fld[i][j]
        arr << [i, j] 
        f = false
      end
    end
  end
  arr.each{ |i, j| change(i, j); $fld[i][j] = 0 }
  ret += 1 unless f
end
p ret