#include<stdio.h>
#include<algorithm>

using namespace std;

int N;
int x[100][100];
int y[100][100];
int f[100][100];
int cnt;

bool input() {
  int i, j;

  scanf("%d", &N);
  if (!N) return false;
  for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
      scanf("%d %d", &x[i][j], &y[i][j]);
    }
  }

  return true;
}

int main(){
  int i, j, a, b, tmp, k, l;

  while(input()){
    cnt = 0;
    fill(f[0], f[0] + 100 * 100, 0);

    for (i = 0; i < N; i++) {
      for (j = 0; j < N; j++) {
        if (f[i][j] != 0) continue;
        f[i][j]++;
        a = x[i][j];
        b = y[i][j];
        while (true) {
          if (f[b][a] == -1 || f[b][a] == 2) break;
          f[b][a]++;
          if (f[b][a] == 2) {
            cnt++;
            break;
          }
          tmp = x[b][a];
          b   = y[b][a];
          a   = tmp;
        }

        for (k = 0; k < N; k++) {
          for (l = 0; l < N; l++) {
            if (f[k][l] == 1) f[k][l] = -1;
          }
        }

      }
    }

    printf("%d\n", cnt);

  }
  return 0;
}