#include<iostream>
using namespace std;

int n;
int floor[100][100];
int x[100][100],y[100][100];

bool rec(int h,int w, int c){

  floor[h][w] = c;

  int tmp = floor[y[h][w]][x[h][w]];
  if(tmp == c)return true;
  else if(tmp < c){
    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
	if(floor[i][j] == c)floor[i][j] = tmp;
      }
    }
    return false;
  }else{
    return rec(y[h][w],x[h][w],c);
  }
}

int main(){
  while(1){
    cin >> n;
    if(!n)break;

    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
	cin >> x[i][j] >> y[i][j];
	floor[i][j] = 10000;
      }
    }

    int ans = 0;

    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
	if(floor[i][j] > ans){
	  if(rec(i,j,ans))ans++;
	}
      }
    }

    cout << ans << endl;
  }
}