#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>
#include<set>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef pair<int,int> P;
#define x first
#define y second
int main(){
	int table[] = {1000,500,100};
	int n;
	while(cin >> n , n){
		set< set<P> > ret;
		vector< vector<P> > d(n,vector<P>(n));
		rep(i,n){
			rep(j,n){
				cin >> d[i][j].x >> d[i][j].y;
			}
		}
		rep(i,n)rep(j,n){
		
			P add = make_pair(i,j);
			
			set<P> lp;
			
			while(lp.find(add) == lp.end() ){
				lp.insert(add);
				add = d[add.y][add.x];
			}
			if(add == make_pair(i,j) )ret.insert(lp);
			
		}
		cout << ret.size() << endl;
		
	}
}