#include <iostream>
#include <vector>

using namespace std;
static const int INF = 999999999;
typedef pair<int, int> P;


void solve()
{
	int N;
	while(cin >> N, N)
	{
		vector< vector<P> > field(N, vector<P>(N));
		vector< vector<int> > data(N, vector<int>(N));
		for(int i = 0; i < N; ++i)
		{
			for(int j = 0; j < N; ++j)
			{
				cin >> field[i][j].first >> field[i][j].second;
				data[i][j] = INF;
			}
		}
		int ans = 0;
		int count = 0;
		for(int i = 0; i < N; ++i)
		{
			for(int j = 0; j < N; ++j)
			{
				if(data[i][j] == INF)
				{
					int x = j;
					int y = i;
					while(data[y][x] == INF)
					{
						data[y][x] = count;
						int ny = field[y][x].second;
						int nx = field[y][x].first;
						y = ny;
						x = nx;
					}
					if(data[y][x] == count)
					{
						++ans;
					}
					++count;
				}
			}
		}
		cout << ans << endl;
	}
}

int main()
{
	solve();
	return(0);
}