import java.util.*


data class Node(val idx:Int) {
    var l : Node? = null
    var r : Node? = null
    var t : Node? = null
    var b : Node? = null
}
fun main() {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    val size = n*n
    val arr = Array(size){Node(it)}

    for(i in 0 until size) {
        if((i + 1) % n > 0) {
            arr[i].r = arr[i+1]
        }
        if(i % n > 0) {
            arr[i].l = arr[i-1]
        }
        if(i + n < size) {
            arr[i].b = arr[i+n]
        }
        if(i - n >= 0) {
            arr[i].t = arr[i-n]
        }
    }

    fun exitTheatre(idx:Int): Int {
        val hate = if(arr[idx].l == null || arr[idx].r == null || arr[idx].t == null || arr[idx].b == null) {
            0
        } else {
            var cur : Node? = arr[idx]
            val list = ArrayList<Int>()
            var cnt = -1
            while(cur != null) {
                cur = cur.l
                ++cnt
            }
            list.add(cnt)

            cur = arr[idx]
            cnt = -1
            while (cur != null) {
                cur = cur.r
                ++cnt
            }
            list.add(cnt)

            cur = arr[idx]
            cnt = -1
            while (cur != null) {
                cur = cur.t
                ++cnt
            }
            list.add(cnt)

            cur = arr[idx]
            cnt = -1
            while (cur != null) {
                cur = cur.b
                ++cnt
            }
            list.add(cnt)
            val x = list.min()!!
            if( x <= 0){while(true){}}
            x
        }
        val node = arr[idx]
        if(node.l != null) {
            node.l!!.r = node.r
        }
        if(node.r != null) {
            node.r!!.l = node.l
        }
        if(node.t != null) {
            node.t!!.b = node.b
        }
        if(node.b != null) {
            node.b!!.t = node.t
        }
      
      node.l = null
        node.r = null
        node.t = null
        node.b = null

        return hate
    }

    var ans = 0
    for(i in 0 until size) {
        val p = sc.nextInt() - 1
        val hate =exitTheatre(p)
      //  println("${p}, $hate")
        ans += hate
    }
    print(ans)



}
