#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <cfloat>
#include <ctime>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <numeric>
#include <list>

using namespace std;

#ifdef _MSC_VER
#define __typeof__ decltype
template <class T> int __builtin_popcount(T n) { return n ? 1 + __builtin_popcount(n & (n - 1)) : 0; }
#endif

#define foreach(it, c) for (__typeof__((c).begin()) it=(c).begin(); it != (c).end(); ++it)
#define all(c) (c).begin(), (c).end()
#define rall(c) (c).rbegin(), (c).rend()
#define popcount __builtin_popcount

#define rep(i, n) for (int i = 0; i < n; ++i)

template <class T> void max_swap(T& a, const T& b) { a = max(a, b); }
template <class T> void min_swap(T& a, const T& b) { a = min(a, b); }

typedef long long ll;
typedef pair<int, int> pint;

const double PI = acos(-1.0);


int main()
{
	int n;
	while (cin >> n, n)
	{
		int tx[128][128], ty[128][128];
		rep (i, n)
			rep (j, n)
				cin >> tx[i][j] >> ty[i][j];

		int visit[128][128];
		memset(visit, -1, sizeof(visit));

		int res = 0;
		for (int y = 0; y < n; ++y)
		{
			for (int x = 0; x < n; ++x)
			{
				int mark = n * y + x;
				if (visit[y][x] == -1)
				{
					int cx = x, cy = y;
					while (visit[cy][cx] == -1)
					{
						visit[cy][cx] = mark;
						int xx = cx, yy = cy;
						cx = tx[yy][xx];
						cy = ty[yy][xx];

						if (visit[cy][cx] == mark)
							++res;
					}
				}
			}
		}
		cout << res << endl;
	}
}