
def g(a,p) a[0]<p ? [p,1] : a[0]>p ? a : [a[0],a[1]+1] end
def f(a,i,j)
  return [0,0] if a[i][4]
  a[i][4]=true
  g(f(a,a[i][a[i][0]===j ? 2 : 0],i),a[i][a[i][0]===j ? 3 : 1])
end

while (n=gets.to_i)!=0
  a=Array.new(n){gets.split.map(&:to_i) << false}

  if a.select{|b| b.size!=5}.size!=0
    puts -1
    next
  end

  puts n.times.inject(1){|pi,i|
    next pi if a[i][4]
    a[i][4]=true
    pi*g(f(a,a[i][0],i),a[i][1])[1]%1007
  }
end