def count(field, y, x)
  result = 1
  color = field[y][x]
  field[y][x] = "."
  dy = [-1, 1, 0, 0]
  dx = [0, 0, -1, 1]
  for i in 0...4 do
    result += count(field, y + dy[i], x + dx[i]) if field[y + dy[i]][x + dx[i]] == color
  end
  field[y][x] = color
  result
end

def vanish(field, y, x)
  color = field[y][x]
  field[y][x] = "."
  dy = [-1, 1, 0, 0]
  dx = [0, 0, -1, 1]
  for i in 0...4 do
    vanish(field, y + dy[i], x + dx[i]) if field[y + dy[i]][x + dx[i]] == color
    field[y + dy[i]][x + dx[i]] = "." if field[y + dy[i]][x + dx[i]] == "O"
  end
end

def delete!(field)
  deleted = false
  for i in 1..H do
    for j in 1..W do
      next if field[i][j] == "." || field[i][j] == "O"
      next if count(field, i, j) < 4
      vanish(field, i, j)
      deleted = true
    end
  end
  deleted
end

def fall!(field)
  for j in 1..W do
    H.downto(1) do |i|
      next if field[i][j] != "."
      i.downto(1) do |k|
        next if field[k][j] == "."
        field[i][j], field[k][j] = field[k][j], field[i][j]
        break
      end
    end
  end
end

H = 12
W = 6
gets.to_i.times do
  field = Array.new(H + 2) {Array.new(W + 2, ".")}
  for i in 1..H do
    field[i][1, W] = gets.chomp.chars
  end

  chain = 0
  while delete!(field) do
    fall!(field)
    chain += 1
  end
  puts chain
end