#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <string>
#include <cmath>
#include <complex>
#include <map>
using namespace std;

#define rep(i,n) for(int i=0;i<int(n);++i)
#define ALL(v) (v).begin(),(v).end()
#define PB push_back
#define EPS 1e-8
#define F first
#define S second

static const double PI=6*asin(0.5);
typedef long long ll;
typedef complex<double> CP;
typedef pair<int,int> P;
static const int INF=1<<24;


int main(){
	int n;
	P m[110][110];
	int vi[110][110];
	while(cin>>n,n){
		rep(i,110){
			rep(j,110){
				m[i][j].F=0;
				m[i][j].S=0;
				vi[i][j]=0;
			}
		}
		rep(i,n){
			rep(j,n){
				cin>>m[i][j].F>>m[i][j].S;
			}
		}
		int x,y;
		int res=0;
		rep(i,n){
			rep(j,n){
				x=j;
				y=i;
				rep(k,n*n){
					P tmp=m[y][x];
					x=tmp.F;
					y=tmp.S;
				}
				if(vi[y][x]==0){
					res++;
					rep(k,n*n+10){
						if(vi[y][x]==1){
							break;
						}
						vi[y][x]=1;
						P tmp=m[y][x];
						x=tmp.F;
						y=tmp.S;
					}
				}
			}
		}
		cout<<res<<endl;
	}
	return 0;
}