import java.util.*

fun main(args:Array<String>):Unit {
    while(true){
        val n = readLine()!!.trim().toInt()
        if (n == 0) return
        val floor = Floor(Array(n){
            val a = readLine()!!.trim().split(' ').map(String::toInt).toIntArray()
            (0 until n).map{
                Point(a[it * 2], a[it * 2 + 1])
            }.toTypedArray()
        })
        var loopCount = 0
        val isLooped = Array(n){Array(n){false}}
        for (x in 0 until n) for (y in 0 until n){
            if (!isLooped[y][x]){
                var single = Point(x, y)
                var double = floor[Point(x, y)]
                while (single != double){
                    single = floor[single]
                    double = floor[floor[double]]
                }
                if (!isLooped[single.y][single.x]){
                    ++loopCount
                    do{
                        isLooped[single.y][single.x] = true
                        single = floor[single]
                    }while(single != double)
                }
            }
        }
        println(loopCount)
    }
}
data class Point(val x:Int, val y:Int)
class Floor(private val mFloorState:Array<Array<Point>>){
    operator fun get(point:Point):Point = mFloorState[point.y][point.x]
}

