#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;

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

int dfs(int i, int j){
	if(used[i][j] == 1){
		used[i][j] = 2;
		return 1;
	}
	if(used[i][j] == 2) return 0;
	used[i][j] = 1;
	int res = dfs(y[i][j], x[i][j]);
	used[i][j] = 2;
	return res;
}

int solve(){
	int res = 0;
	memset(used, 0, sizeof(used));
	for(int i=0; i<n; i++){
		for(int j=0; j<n; j++){
			if(used[i][j]) continue;
			res += dfs(i, j);
		}
	}
	return res;
}

int main(){
	while(1){
		cin >> n;
		if(n==0) break;
		
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				cin >> x[i][j] >> y[i][j];
			}
		}
		cout << solve() << endl;
	}
	return 0;
}
