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

int nxt_x[110][110], nxt_y[110][110], checked[110][110];

int main() {
  int N;
  while(cin >> N, N) {
    memset(nxt_x, 0, sizeof(nxt_x));
    memset(nxt_y, 0, sizeof(nxt_y));
    memset(checked, 0, sizeof(checked));
    
    for(int i=0; i<N; i++) {
      for(int j=0; j<N; j++) {
        int col, row; cin >> col >> row;
        nxt_x[i][j] = row;
        nxt_y[i][j] = col;
      }
    }

    int ans = 0;
    for(int i=0; i<N; i++) {
      for(int j=0; j<N; j++) {
        if(checked[i][j]) continue;
        int id = ans + 1, res = -1;
        int x = i, y = j;

        while(1) {
          int nx = nxt_x[x][y];
          int ny = nxt_y[x][y];

          // printf("(x, y) = %d, (nx, ny) = %d, id = %d\n", x, y, nx, ny, checked[nx][ny]);
          if(checked[nx][ny] == 0) {
            checked[nx][ny] = id;
          }
          else {
            if(checked[nx][ny] == id) {
              ans++;
            }
            res = checked[nx][ny];
            break;
          }

          x = nx, y = ny;
        }

        x = i, y = j;
        while(1) {
          if(checked[x][y] == res) break;
          checked[x][y] = res;
          int nx = nxt_x[x][y], ny = nxt_y[x][y];
          x = nx, y = ny;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}

