def complete?(floppy_cube)
  for i in 1...9
    return false if floppy_cube[i - 1] != floppy_cube[i]
  end

  for i in 10...12
    return false if floppy_cube[i - 1] != floppy_cube[i]
  end

  for i in 13...15
    return false if floppy_cube[i - 1] != floppy_cube[i]
  end

  for i in 16...18
    return false if floppy_cube[i - 1] != floppy_cube[i]
  end

  for i in 19...21
    return false if floppy_cube[i - 1] != floppy_cube[i]
  end

  for i in 22...30
    return false if floppy_cube[i - 1] != floppy_cube[i]
  end

  true
end

def rotate(floppy_cube, i)
  p_index = [
    [15, 0, 3, 6, 9],
    [18, 2, 1, 0, 15],
    [12, 8, 5, 2, 18],
    [9, 6, 7, 8, 12]
  ]
  n_index = [
    [17, 23, 26, 29, 20],
    [20, 29, 28, 27, 14],
    [14, 27, 24, 21, 11],
    [11, 21, 22, 23, 17]
  ]

  clone = floppy_cube.dup

  5.times do |j|
    clone[p_index[i][j]], clone[n_index[i][j]] = clone[n_index[i][j]], clone[p_index[i][j]]
  end

  clone
end

def dfs(floppy_cube, depth = 0)
  return Float::INFINITY if depth > 8
  return depth if complete?(floppy_cube)

  res = Float::INFINITY

  for i in 0...4
    res = [res, dfs(rotate(floppy_cube, i), depth + 1)].min
  end

  res
end

while line = gets
  n = line.chomp.to_i

  n.times do
    floppy_cube = gets.chomp.split.map(&:to_i)
    puts dfs(floppy_cube)
  end
end