require 'set'

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

def check2 arr
  return 0 if check arr
  s = Set.new
  s.add arr
  q = []
  q << [arr, 0]
  loop do
    arr, cnt = q.shift
    MV.each do |a|
      tmp = arr.dup
      5.times{ |i| tmp[a[i]], tmp[a[5+i]] = tmp[a[5+i]], tmp[a[i]] }
      return cnt + 1 if check tmp
      unless s.include? tmp
        q << [tmp, cnt + 1] 
        s.add tmp
      end
    end
  end
end
 
gets.to_i.times do
  p check2 gets.split(" ").map(&:to_i) 
end