h, w = gets.split.map(&:to_i)
a = (1..h).map { gets.split("").map(&:to_i) }

queue = []
(1..h-1).each do |i|
    (0..w-1).each do |j|
        next if a[i][j] == 0
        (i-1..i+1).each do |y|
            (j-1..j+1).each do |x|
                a[i][j] -= 1 if a[y][x] == 0
            end
        end
        if a[i][j] <= 0
            queue << [i, j]
            a[i][j] = 'd'
        end
    end
end
queue.each do |i, j|
    a[i][j] = 0
end

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
                if a[y][x] != ?d && a[y][x] > 0
                    a[y][x] -= 1
                    if a[y][x] <= 0
                        new_queue << [y, x]
                        a[y][x] = ?d
                    end
                end
            end
        end
    end
    queue = new_queue
    queue.each do |i, j|
        a[i][j] = 0
    end
    count += 1
end
p count

