from collections import deque
import heapq

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

def bfs(loc):
    data = [-1]*(N**2)
    data[loc] = 1
    ans = N**2
    s = P[loc]
    stack = [[0, loc]]
    while stack:
        d, v = heapq.heappop(stack)
        # 上
        if v-N >= 0:
            if data[v-N] == -1:
                data[v-N] = 1
                if s < P[v-N]:
                    heapq.heappush(stack, [d+1, v-N])
                else:
                    heapq.heappush(stack, [d, v-N])
        else:
            return d
            # ans = min(ans, d)
        # 左
        if v%N != 0:
            if data[v-1] == -1:
                data[v-1] = 1
                if s < P[v-1]:
                    heapq.heappush(stack, [d+1, v-1])
                else:
                    heapq.heappush(stack, [d, v-1])
        else:
            return d
            # ans = min(ans, d)
        # 右
        if (v+1)%N != 0 and v != N**2-1:
            if data[v+1] == -1:
                data[v+1] = 1
                if s < P[v+1]:
                    heapq.heappush(stack, [d+1, v+1])
                else:
                    heapq.heappush(stack, [d, v+1])
        else:
            return d
            # ans = min(ans, d)
        # 下
        if v+N < N**2:
            if data[v+N] == -1:
                data[v+N] = 1
                if s < P[v+N]:
                    heapq.heappush(stack, [d+1, v+N])
                else:
                    heapq.heappush(stack, [d, v+N])
        else:
            return d
            # ans = min(ans, d)
    return ans

ans = 0
for i in range(N**2):
    ans += bfs(i)
print(ans)