import sys
input = sys.stdin.readline

n = int(input())
P = list(map(int,input().split()))
for i in range(n**2):
    P[i] -= 1

M = [[] for i in range(n**2 + 1)]
DD = [[-1,0],[1,0],[0,1],[0,-1]]
for i in range(n**2):
    x = i//n
    y = i%n
    for d in range(4):
        gx = x + DD[d][0]
        gy = y + DD[d][1]
        if 0 <= gx < n and 0 <= gy < n:
            g = gx*n + gy
            M[i].append([g, 1])

for i in range(n**2):
    x = i//n
    y = i%n
    if x == 0 or x == n-1 or y == 0 or y == n-1:
        M[i].append([n**2, 0])

# print(M)

ans = 0
import heapq
nn = len(M)
for ii in range(n**2):
    s = P[ii]

    D = [10**9] * nn  # 頂点0からの距離
    # P = [-1] * n  # 頂点0からの最短距離において、そこの直前の頂点(経路復元に利用)
    D[s] = 0
    V = [0] * nn  # その頂点のD[i]が最短距離と確定したら1
    Q = []  # 優先度付きキュー
    # for v in range(nn):
    #     heapq.heappush(Q, [D[v], v])
    heapq.heappush(Q, [D[s], s])

    le = len(Q)
    while len(Q) > 0:
        # print(Q,D)
        q = heapq.heappop(Q)
        u = q[1]
        du = q[0]
        if V[u] == 0:
            V[u] = 1
            le -= 1
            for i in range(len(M[u])):
                v = M[u][i][0]
                luv = M[u][i][1]
                if V[v] == 0:
                    alt = du + luv
                    if D[v] > alt:
                        D[v] = alt
                        # P[v] = u
                        heapq.heappush(Q, [alt, v])

    ans += D[n**2]
    # print(ans)
    # print(P,n)
    x = P[ii]//n
    y = P[ii]%n
    # print(P,P[ii],x,y)
    for d in range(4):
        gx = x + DD[d][0]
        gy = y + DD[d][1]
        # print(gx,gy)
        if 0 <= gx < n and 0 <= gy < n:
            g = gx*n + gy
            # print("g",g)
            for j in range(len(M[g])):
                if M[g][j][0] == P[ii]:
                    M[g][j][1] = 0
                    # print("ok")

print(ans)