import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;
 
void main() {
    struct P { int x, y; }
    int N; 
    P[][] F;
    bool input() {
        scanf("%d\n", &N);
        if (N == 0) return false;
        F = new P[][](N, N);
        foreach (i; 0 .. N) {
            foreach (j; 0 .. N) {
                P p; scanf("%d %d", &p.x, &p.y);
                F[i][j] = p;
            }
        }
        return true;
    }

    void solve() {
        auto used = new bool[][](N, N);
        auto loop = new bool[][](N, N);
        bool dfs(int oy, int ox, int y, int x) {
            if (y == oy && x == ox) return true;
            if (used[y][x]) return false;
            if (loop[y][x]) return false;
            used[y][x] = true;
            return dfs(oy, ox, F[y][x].y, F[y][x].x);
        }
        void fillLoop(int y, int x) {
            if (loop[y][x]) return;
            loop[y][x] = true;
            fillLoop(F[y][x].y, F[y][x].x);
        }
        int C = 0;
        foreach (i; 0 .. N) {
            foreach (j; 0 .. N) {
                foreach (k; 0 .. N) used[k][] = false;
                if (dfs(i, j, F[i][j].y, F[i][j].x)) {
                    C++;
                    fillLoop(i, j);
                }
            }
        }
        writeln(C);
    }

    while (input) solve;
}