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

queue = []
castle.keys.each do |key|
    i, j = key
    n = (i-1..i+1).to_a.product((j-1..j+1).to_a).select {|y, x| !castle[[y, x]]}.size
    castle[key] -= n
    queue << key if castle[key] <= 0
end
castle.delete_if {|_, k| k <= 0}

count = 0
until queue.empty?
    new_queue = []
    queue.each do |i, j|
        (i-1..i+1).each do |y|
            (j-1..j+1).each do |x|
                next if y == i && x == j
                key = [y, x]
                if castle[key]
                    castle[key] -= 1
                    if castle[key] <= 0
                        new_queue << key
                        castle.delete(key)
                    end
                end
            end
        end
    end
    queue = new_queue
    count += 1
end
p count

