$sandpool = []
$check_points = []
$wave_count = 0
$break_points = []

def breakable?(castle)
    1 <= castle && castle < 9
end

def search_around(px, py)
    ((px - 1)..(px + 1)).each do |x|
        ((py - 1)..(py + 1)).each do |y|
            next if x == px && y == py
            yield(x, y)
        end
    end
end

def check_break_points
    $check_points.each do |i, j|
        castle = $sandpool[i][j]
        search_around(i, j) do |pi, pj|
            break if castle == 0
            castle -= 1 if $sandpool[pi][pj] == 0
        end
        $break_points << [i, j] if castle == 0
    end
end

def break_castles
    $break_points.each do |i, j|
        $sandpool[i][j] = 0
    end
end

def setup_next_check_points
    $check_points = []
    $break_points.each do |i, j|
        search_around(i, j) do |pi, pj|
            castle = $sandpool[pi][pj]
            $check_points << [pi, pj] if breakable?(castle)
        end
    end
    $check_points.uniq!
end

def broken?
    bool = $break_points.length > 0
    $break_points = []
    $wave_count += 1 if bool
    bool
end

def wave
    check_break_points
    break_castles
    setup_next_check_points
    broken?
end

#initialize
row, column = gets.split(" ").map(&:to_i)
row.times do
    ar = []
    gets.chomp.each_char do |char|
        ar << (char == "." ? 0 : char.to_i)
    end
    $sandpool << ar
end
(1..(row - 2)).each do |i|
    (1..(column - 2)).each do |j|
        castle = $sandpool[i][j]
        $check_points << [i, j] if breakable?(castle)
    end
end
#count
is_broken = true
while is_broken
    
    is_broken = wave
end
#output
puts $wave_count

