def check_broken(width, height, maps, strength)
  count = 0
  (-1..1).each do |i|
    (-1..1).each do |j|
      next if i ==0 && j == 0
      if maps[width + i][height + j].zero?
        strength -= 1 
      end
      if strength < 1
        return true
      end
    end
  end
  return false
end

def check_can_break_area(start_width, end_width, start_height, end_height, maps)
  can_break_area = []
  for i in (start_width..end_width)
    for j in (start_height..end_height)
      strength = maps[i][j]
      next if strength.zero?
      can_break_area << [i, j] if 1 <= strength && strength < 9
    end
  end
  can_break_area
end

w, h = gets.split(" ").map(&:to_i)
maps = []
w.times do |i|
  chara = []
  gets.chomp.each_char do |char|
    if char == "." || (char.to_i) > 0
      chara << char.to_i
    end
  end
  maps << chara
end
can_break_area = check_can_break_area(1, w - 2, 1, h - 2, maps)
wave = 0
while true
  next_can_break_area = []
  can_break_area.each do |width, height|
    strength = maps[width][height]
    next_can_break_area << [width, height] if check_broken(width, height, maps, strength)
  end
  can_break_area = []
  next_can_break_area.each do |width, height|
    maps[width][height] = 0
  end
  next_can_break_area.each do |width, height|
    can_break_area += check_can_break_area(-1 + width, 1 + width, -1 + height, 1 + height, maps)
  end
  if next_can_break_area.length > 0
    wave += 1
  else
    break
  end
  can_break_area.uniq!
end

puts wave
