#include <iostream>
#include <cstring>
using namespace std;

int n;
int x[102][102], y[102][102];
int t[102][102];

void solve(){
  memset(t, -1, sizeof(t));

  int now = 0;
  int res = 0;

  for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
      if(t[i][j] != -1) continue;

      int now_x = j;
      int now_y = i;

      while(t[now_y][now_x] == -1){
        t[now_y][now_x] = now;
        int nx = x[now_y][now_x];
        int ny = y[now_y][now_x];
        now_x = nx;
        now_y = ny;
      }

      if(t[now_y][now_x] == now){
        res++;
      }

      now++;
    }
  }

  cout << res << endl;
}

int main(){
  while(cin >> n, n){
    for(int i = 0; i < n; i++){
      for(int j = 0; j < n; j++){
        cin >> x[i][j] >> y[i][j];
      }
    }
    solve();
  }
}