h, w = gets.split.map(&:to_i)
fld = Array.new(h){ Array.new(w) }
arr = []
h.times do |i|
   str = gets.chomp
   w.times do |j|
    if str[j] == '.'
      fld[i][j] = -1
      arr << [0, [i, j]]
    else fld[i][j] = str[j].to_i
    end
  end
end
ret = 0
until arr.empty?
  cnt, pos = arr.shift
  y, x = pos
  ret = [ret, cnt].max
  (-1..1).each do |i|
    (-1..1).each do |j|
      p = i+y; q = j+x
      next if i == 0 && j == 0 || p < 0 || p >= h || q < 0 || q >= w || fld[p][q] <= 0
      fld[p][q] -= 1
      arr << [cnt+1, [p, q]] if fld[p][q] == 0
    end
  end
end
p ret