def check(arr)
  a =[0,9,12,15,18,21,30]
  a.each_cons(2){|s,t| return false if (s...t).any?{ |i| arr[i] != arr[s] } }
  true
end

MV = [[0,1,2,14,18,27,28,29,15,20],
      [6,7,8,12,9,21,22,23,17,11],
      [0,3,6,9,15,23,26,29,20,17],
      [2,5,8,11,12,21,24,27,18,14]]
  
gets.to_i.times do
  cube = gets.split(" ").map(&:to_i)
  q = []
  q << [cube, 0]
  until q.empty?
    tmp, cnt = q.shift
    if check tmp
      p cnt
      break
    end
    MV.each do |arr|
      tmp2 = tmp.dup
      arr[0,5].zip(arr[5,5]).each do |a, b|
        tmp2[a], tmp2[b] = tmp2[b], tmp2[a]
      end
      q << [tmp2, cnt+1] unless q.include? tmp2
    end
  end
end