#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <queue>
#include <map>
#include <vector>
using namespace std;


class Point{
public:
  int x, y;
};

int cnt;
Point data[100][100];
bool visited[100][100];
bool loop[100][100];


void rec(int x, int y, int sx, int sy) {
  if(loop[y][x]) return;
  if(visited[y][x]) {
    if(x == sx && y == sy) {
      cnt++;
      loop[y][x] = true;
    }
    return;
  }
  visited[y][x] = true;
  rec(data[y][x].x, data[y][x].y, sx, sy);
}

int main() {
  while(1) {
    int N;
    cin >> N;
    if(N == 0) break;
    for(int i = 0; i < N; i++) {
      for(int j = 0; j < N; j++) {
	cin >> data[i][j].x >> data[i][j].y;
      }
    }

    cnt = 0;

    fill(&loop[0][0], &loop[N-1][N-1]+1, false);
    for(int i = 0; i < N; i++) {
      for(int j = 0; j < N; j++) {
	fill(&visited[0][0], &visited[N-1][N-1]+1, false);
	rec(j, i, j, i);
      }
    }

    cout << cnt << endl;
  }
  return 0;
}