#include <iostream>
#include <map>
using namespace std;
int main(){
  
  pair <int,int> tile[100][100];
  int n,hata[100][100],i,j,x,y,result,a;
  
  while(cin>>n,n){
  
  for(i=0;i<n;i++) for(j=0;j<n;j++){
      cin>>x>>y;
      tile[i][j]=make_pair(x,y);
    }
   for(i=0;i<n;i++) for(j=0;j<n;j++) hata[i][j]=20000;
  
  result=0;
  a=0;
  for(i=0;i<n;i++) for(j=0;j<n;j++){
      if(hata[i][j]==20000){
        a++;
        //cout<<a<<endl;
        y=i;
        x=j;
        result++;
        while(1){
          if(hata[y][x]<a){
            result--;
            break;
          } else if(hata[y][x]==a) break;
          hata[y][x]=a;
          int y1=y,x1=x;
          y=tile[y1][x1].second;
          x=tile[y1][x1].first;
        
        }
      }
    }
  cout<<result<<endl;
  }
  
  return 0;
  
}

  