h, w = gets.split.map(&:to_i)
castle = {}
(0..h-1).each do |i|
    l = gets.chomp
    (0..w-1).each do |j|
        c = l[j]
        if c != ?.
            castle[[i, j]] = c.to_i
        end
    end
end
count = 0
loop do
    unchanged = true
    new_castle = {}
    castle.each do |key, s|
        i, j = key
        n = (i-1..i+1).to_a.product((j-1..j+1).to_a).select {|y, x| !castle[[y, x]]}.size
        if n >= s
            unchanged = false
        else
            new_castle[key] = s
        end
    end
    break if unchanged
    count += 1
    castle = new_castle
end
p count
