#include<stdio.h>
int main(){
  int n,a,b,i,j,x,y,c;
  while(scanf("%d",&n),n){
    int p[10001]={0};
    int d[10001]={0};
    for(i=c=0;i<n;i++){
      for(j=0;j<n;j++){
	scanf("%d %d",&x,&y);
	for(a=i*100+j+1;p[a];a=p[a]);
	for(b=y*100+x+1;p[b];b=p[b]);
	if(a-b){
	  if(d[b]< d[a])p[b]=a;
	  if(d[b]>=d[a])p[a]=b;
	  if(d[a]==d[b])d[b]++;
	  c++;
	}
      }
    }
    printf("%d\n",n*n-c);
  }
  return 0;
}