#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<cassert>
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<utility>
#include<numeric>
#include<algorithm>
#include<bitset>
#include<complex>

using namespace std;

typedef long long Int;
typedef vector<int> vint;
typedef pair<int,int> pint;
#define mp make_pair

template<class T> void pv(T a, T b) { for (T i = a; i != b; ++i) cout << *i << " "; cout << endl; }
template<class T> void chmin(T &t, T f) { if (t > f) t = f; }
template<class T> void chmax(T &t, T f) { if (t < f) t = f; }
int in() { int x; scanf("%d", &x); return x; }

struct Pt{
	int x,y;
	Pt(){}
	Pt(int x,int y):x(x),y(y){}
};

int checked[110][110];

int main() {
	int n;
	Pt mp[110][110];
	for(;n=in();){
		int x,y;
		for(y=0;y<110;y++){
			for(x=0;x<110;x++){
				mp[y][x].x=0;
				mp[y][x].y=0;
			}
		}for(y=0;y<n;y++){
			for(x=0;x<n;x++){
				mp[y][x].x=in();
				mp[y][x].y=in();
			}
		}
		Pt pt;
		memset(checked,0,sizeof(checked));
		int res=0;
		for(y=0;y<n;y++){
			for(x=0;x<n;x++){
				if(checked[y][x])continue;
				int i;
				pt=mp[y][x];
				for(i=0;i<10010;i++){
					pt=mp[pt.y][pt.x];
					if(pt.x==x&&pt.y==y)break;
				}
				//cout<<pt.x<<" "<<pt.y<<" "<<x<<" "<<y<<endl;
				if(i<10010){
					res++;
					for(i=0;i<10010;i++){
						checked[pt.y][pt.x]=1;
						pt=mp[pt.y][pt.x];
						if(pt.x==x&&pt.y==y)break;
					}
				}else checked[y][x]=1;
				//int xx,yy;
				/*for(yy=0;yy<n;yy++){
					for(xx=0;xx<n;xx++){
						cout<<checked[yy][xx];
					}
					cout<<endl;
				}
				cout<<endl;*/
			}
		}
		cout<<res<<endl;
	}
}