#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
const int INF = 1<<29;

int main() {
  int n;
  while(cin>>n,n) {
    int bax[n][n], bay[n][n];
    REP(i,n) {
      REP(j,n) {
        cin >> bax[j][i] >> bay[j][i];
      }
    }
    int res = 0;
    int visited[n][n];
    memset(visited,0,sizeof(visited));
    int cnt = 1;
    REP(y,n) {
      REP(x,n) {
        if (visited[x][y]) continue;
        int xx = x, yy = y;
        while(!visited[xx][yy]) {
          visited[xx][yy] = cnt;
          int tmp = bax[xx][yy];
          yy = bay[xx][yy];
          xx = tmp;
        }
        if (visited[xx][yy] == cnt) {
          //  cout << xx <<" " << yy << endl;
          res++;
        }
        cnt++;
      }
    }
    cout << res << endl;
  }
}