def dark?(map)
  map.all? { |r| r.all? { |elt| elt == '#' } }
end

def step(map)
  h = map.size
  w = map[0].size
  out = Array.new(h) { Array.new(w, '.') }

  0.upto(h-1) do |i|
    0.upto(w-1) do |j|

      if map[i][j] == '#'
        -1.upto(1) do |di|
          -1.upto(1) do |dj|
            if di * dj == 0 &&
              (i+di).between?(0, h-1) &&
               (j+dj).between?(0, w-1)
              out[i+di][j+dj] = '#'
            end
          end
        end
      end

    end
  end

  out
end

h, w = gets.split.map(&:to_i)

map = h.times.map {
  gets.chomp.chars
}

count = 0
until dark?(map)
  map = step(map)
  count += 1
end

p count
