#include <iostream>
#include <vector>
#include <stack>
using namespace std;

#define loop(i,a,b) for(int i=(a); i<int(b); i++)
#define rep(i,b) loop(i,0,b)
#define iter(it,c) for(auto it=c.begin(); it!=c.end(); it++)
typedef vector<int> vi;
typedef vector<vi> vvi;

void visit(const vvi &g, int v, vvi& scc,
           stack<int> &S, vector<bool> &inS,
           vector<int> &low, vector<int> &num, int& time) {
    low[v] = num[v] = ++time;
    S.push(v); inS[v] = true;
    iter(e, g[v]) {
        int w = *e;
        if (num[w] == 0) {
            visit(g, w, scc, S, inS, low, num, time);
            low[v] = min(low[v], low[w]);
        } else if (inS[w])
            low[v] = min(low[v], num[w]);
    }
    if (low[v] == num[v]){
        scc.push_back(vi());
        while (1) {
            int w = S.top(); S.pop(); inS[w] = false;
            scc.back().push_back(w);
            if (v == w) break;
        }
    }
}

void scc(vvi const& g, vvi& res) {
    int const n = g.size();
    vi num(n), low(n);
    stack<int> S;
    vector<bool> inS(n);
    int time = 0;
    rep(u,n)if(num[u]==0) visit(g, u, res, S, inS, low, num, time);
}

int main(){
    int n;
    while(cin>>n,n){
        vvi g(n*n);
        rep(i,n)rep(j,n){
            int x,y; cin>>x>>y;
            int u=i*n+j;
            int v=y*n+x;
            g[u].push_back(v);
        }
        vvi ans;
        scc(g,ans);
        int c=0;
        rep(i,ans.size()){
            if(ans[i].size()==1){
                if(g[ans[i][0]][0]!=ans[i][0]) c++;
            }
        }
        cout << ans.size()-c << endl;
    }
}