H = 12
W = 6
X = "."
O = "O"

def count!(field, y, x)
  color = field[y][x]
  field[y][x] = X
  nex = [[-1, 0], [1, 0], [0, -1], [0, 1]].map{|dy, dx| [y + dy, x + dx]}
  1 + nex.map{|ny, nx| field[ny][nx] != color ? 0 : count!(field, ny, nx)}.inject(:+)
end

def count(field, y, x)
  count!(Marshal.load(Marshal.dump(field)), y, x)
end

def vanish!(field, y, x)
  color = field[y][x]
  field[y][x] = X
  nex = [[-1, 0], [1, 0], [0, -1], [0, 1]].map{|dy, dx| [y + dy, x + dx]}
  nex.each do |ny, nx|
    field[ny][nx] = X if field[ny][nx] == O
    vanish!(field, ny, nx) if field[ny][nx] == color
  end
end

def uyenimo!(field)
  done = false
  1.upto(H) do |y|
    1.upto(W) do |x|
      next if field[y][x] == X || field[y][x] == O
      next if count(field, y, x) < 4
      vanish!(field, y, x)
      done = true
    end
  end
  done
end

def fall!(field)
  1.upto(W) do |x|
    H.downto(1) do |y|
      next unless field[y][x] == X
      y.downto(1) do |i|
        next if field[i][x] == X
        field[y][x], field[i][x] = field[i][x], field[y][x]
        break
      end
    end
  end
end

gets.to_i.times do
  field = Array.new(H + 2){X * (W + 2)}
  field[1, H] = H.times.map{X + gets.chomp + X}
  chain = 0
  while uyenimo!(field) do
    fall!(field)
    chain += 1
  end
  puts chain
end