hight, width = gets.split(" ").map(&:to_i)
castle = []
hight.times do |hig|
  castle << gets.split("").map(&:to_i)
end

def wave(castle)
  wave_count = 0
  break_array = []
   (1..castle.size).each do |hi|
    next if castle[hi].nil?
     (0..castle.first.size-1).each do |wi|
      next if castle[hi][wi].nil?
      next if castle[hi][wi] == 0 
      next if castle[hi][wi] > 8
      (hi-1..hi+1).each do |y|
        next if castle[y].nil?
        (wi-1..wi+1).each do |x|
          next if castle[y][x].nil?
          if castle[y][x] == 0
            castle[hi][wi] -= 1 
          end
        end
      end
      if 0 >= castle[hi][wi]
        break_array << [hi, wi]
        castle[hi][wi] = "done"
      end
    end
  end
  break_array.each {|h, w| castle[h][w] = 0}
  until break_array.empty?
    next_break_array = []
    break_array.each do |h, w|
      (h-1..h+1).each do |y|
        next if castle[y].nil?
        (w-1..w+1).each do |x|
          next if castle[y][x].nil?
          next if x == w && y == h
          if castle[y][x] != "done" && castle[y][x] > 0
            castle[y][x] -= 1 
            if castle[y][x] <= 0
              next_break_array << [y, x]
              castle[y][x] = "done"
            end
          end
        end
      end
    end
    next_break_array.each {|h, w| castle[h][w] = 0}
    break_array = next_break_array
    wave_count += 1
  end
  wave_count
end
puts wave(castle)
