class Squares
  def initialize
    @height, @width = gets.split.map(&:to_i)
    @entity = Array.new(@height + 2) {Array.new(@width + 2) {'.'}}
    @height.times do |h|
      row = gets.chomp.split('')
      @width.times do |w|
        @entity[h+1][w+1] = row[w]
      end
    end

    @step = 0

    until run
    end
  end

  def display
    puts @step
  end

  def run
    @step += 1

    new_entity = Array.new(@height + 2) {Array.new(@width + 2) {'.'}}
    all_black = true
    (1..@height).each do |h|
      (1..@width).each do |w|
        if is_black?(h, w) || adjoin_black?(h, w)
          new_entity[h][w] = '#'
        else
          all_black = false
        end
      end
    end

    @entity = new_entity
    all_black
  end

  def adjoin_black?(h, w)
    is_black?(h - 1, w) ||
        is_black?(h + 1, w) ||
        is_black?(h, w - 1) ||
        is_black?(h, w + 1)
  end

  def is_black?(h, w)
    @entity[h][w] == '#'
  end
end

Squares.new.display