while n = gets.to_i
  break if n == 0
  tile = n.times.map{ gets.split.map(&:to_i).each_slice(2).to_a.map{ |x, y| y * n + x } }.flatten(1)
  visit = [-1] * (n * n)
  cnt = 0
  m = 0
  while pos = visit.index{ |t| t == -1 }
    loop do
      visit[pos] = m
      pos = tile[pos]
      if visit[pos] != -1
        if visit[pos] == m
          cnt += 1
        end
        break
      end
    end
    m += 1
  end
  p cnt
end