### constant

#     (+x,+y,+z)
DICE = [1, 2, 3]

### subroutines

def rot_x(dc0, n = 1)
  dc = dc0.clone
  n.times.each{tmp = dc[1]; dc[1] = 7 - dc[2]; dc[2] = tmp}
  dc
end

def rot_y(dc0, n = 1)
  dc = dc0.clone
  n.times.each{tmp = dc[2]; dc[2] = 7 - dc[0]; dc[0] = tmp}
  dc
end

def rot_z(dc0, n = 1)
  dc = dc0.clone
  n.times.each{tmp = dc[0]; dc[0] = 7 - dc[1]; dc[1] = tmp}
  dc
end

def right_sum()
  rsum = 0
  for x in (0...3)
    for y in (0...3)
      posz = x * 9 + y * 3
      d = $cbs[posz][2] | $cbs[posz + 1][2] | $cbs[posz + 2][2]
      rsum += d
    end
  end
  rsum
end

def rec(k)
  if k >= 27
    $rsums[right_sum()] = true
    return
  end

  x = k / 9
  y = (k / 3) % 3
  z = k % 3

  posx = k - x * 9
  posy = k - y * 3
  posz = k - z
  xd = $cbs[0 * 9 + posx][0] | $cbs[1 * 9 + posx][0] | $cbs[2 * 9 + posx][0]
  yd = $cbs[0 * 3 + posy][1] | $cbs[1 * 3 + posy][1] | $cbs[2 * 3 + posy][1]
  zd = $cbs[0 * 1 + posz][2] | $cbs[1 * 1 + posz][2] | $cbs[2 * 1 + posz][2]

  cbsk = $cbs[k]

  $alldcs.each do |dc|
    if (xd != 0 && xd != dc[0]) ||
       (yd != 0 && yd != dc[1]) ||
       (zd != 0 && zd != dc[2])
      next
    end

    $cbs[k] = dc
    rec(k + 1)
    $cbs[k] = cbsk
  end
end

### main

$alldcs = []

for zr in (0...4)
  for yr in (0...4)
    for xr in (0...4)
      $alldcs << rot_z(rot_y(rot_x(DICE, xr), yr), zr)
    end
  end
end
$alldcs.sort!.uniq!
$nalldcs = $alldcs.length
#p $alldcs

n = gets.to_i

n.times do
  $cbs = 27.times.map{[0] * 3}

  for y in (0...3)
    tys = gets.split.map(&:to_i)
    for z in (0...3)
      tyz = tys[z]
      next if tyz == 0
      for x in (0...3)
        pos = x * 9 + y * 3 + z
        $cbs[pos][0] = tyz
      end
    end
  end

  for x in (0...3)
    fxs = gets.split.map(&:to_i)
    for z in (0...3)
      fxz = fxs[z]
      next if fxz == 0
      for y in (0...3)
        pos = x * 9 + y * 3 + z
        $cbs[pos][1] = fxz
      end
    end
  end
  #p $cbs; exit

  $rsums = {}

  rec(0)

  rs = $rsums.keys.sort
  puts rs.empty? ? 0 : rs.join(' ')
end