n = '4'.to_i
a = []

n.times do |i|
  a << gets.split.map(&:to_i)
end

day = 0
while true
  break if a.all? {|i| i[0].nil? }
  day += 1
  finish_today = []
  n.times { finish_today << false }
  n.times do |i|
    next_comp = a[i][0]
    next if next_comp.nil? || a[next_comp-1][0].nil?
    if !finish_today[i] && a[next_comp-1][0] == i+1 && !finish_today[next_comp-1]
      finish_today[i] = true
      a[i].shift
      finish_today[next_comp-1] = true
    a[next_comp-1].shift
    end
  end
  if day == n*(n-1)
    day = -1
    break
  end
end
p day
