#include<stdio.h>
int main(){
  int n,i,j,gx,gy,ny,nx,c,b;
  int x[101][101],y[101][101];
  while(scanf("%d",&n),n){
    int f[101][101]={0};
    for(i=0;i<n;i++){
      for(j=0;j<n;j++){
	scanf("%d %d",&x[i][j],&y[i][j]);
      }
    }
    for(i=c=b=0;i<n;i++){
      for(j=0;j<n;j++){
	if(f[i][j])continue;
	gy=i;
	gx=j;
	c++;
	while(f[gy][gx]==0){
	  nx=x[gy][gx];
	  ny=y[gy][gx];
	  f[gy][gx]=c;
	  gx=nx;
	  gy=ny;
	}
	if(f[gy][gx]!=c)b++;
      }
    }
    printf("%d\n",c-b);
  }
  return 0;
}