require 'set'
n = gets.to_i

rot = -> a, i1, i2, i3, i4, i5, i6, i7, i8, x, y do
    a[i1], a[i2], a[i3], a[i4], a[i5], a[i6], a[i7], a[i8] = a[i5], a[i6], a[i7], a[i8], a[i1], a[i2], a[i3], a[i4]
    a[x], a[y] = a[y], a[x]
end

check = -> a do
    a[1..9].uniq.size == 1 &&
    a[10..12].uniq.size == 1 &&
    a[13..15].uniq.size == 1 &&
    a[16..18].uniq.size == 1 &&
    a[19..21].uniq.size == 1
end

n.times do
    queue = [[nil] + gets.split.map(&:to_i)]
    step = 0
    reached = Set[*queue]
    until queue.empty?
        new_queue = []
        add = -> x do
            if !reached.include?(x)
                reached << x
                new_queue << x
            end
        end

        queue.each do |a|
            if check[a]
                puts step
                new_queue = []
                break
            end
            b = a.dup
            rot[b, 16, 1, 2, 3, 15, 28, 29, 30, 19, 21]
            add[b]
            b = a.dup
            rot[b, 18, 7, 8, 9, 13, 22, 23, 24, 10, 12]
            add[b]
            b = a.dup
            rot[b, 21, 1, 4, 7, 10, 24, 27, 30, 16, 18]
            add[b]
            b = a.dup
            rot[b, 19, 3, 6, 9, 12, 22, 25, 28, 13, 15]
            add[b]
        end
        queue = new_queue
        step += 1
    end
end

