# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    P=tuple(map(int1,input().split()))
    c=[[1]*N for _ in range(N)]
    ans=0
    dy,dx=[1,0,-1,0],[0,1,0,-1]
    class UnionFind:
        def __init__(self,n):
            self.par=[i for i in range(n)]
            self.siz=[1]*n
            
        def root(self,x):
            while self.par[x]!=x:
                self.par[x]=self.par[self.par[x]]
                x=self.par[x]
            return x
        
        def unite(self,x,y):
            x=self.root(x)
            y=self.root(y)
            if x==y:
                return False
            if self.siz[x]<self.siz[y]:
                x,y=y,x
            self.siz[x]+=self.siz[y]
            self.par[y]=x
            return True
        
        def is_same(self,x,y):
            return self.root(x)==self.root(y)
        
        def size(self,x):
            return self.siz[self.root(x)]
    u=UnionFind(N**2)
    dist=[INF]*(N**2)
    for p in P:
        que=deque([(p//N,p%N)])
        d=[[INF]*N for _ in range(N)]
        d[p//N][p%N]=0
        f=True
        f2=False
        MAX=INF
        while que and f:
            y,x=que.popleft()
            if f2 and d[y][x]>=MAX:
                tmp=MAX
                break
            for k in range(4):
                ny,nx=(y+dy[k],x+dx[k])
                if 0<=ny<N and 0<=nx<N:
                    if d[ny][nx]==INF:
                        if c[ny][nx]==1:
                            d[ny][nx]=d[y][x]+1
                            que.append((ny,nx))
                        else:
                            MAX=min(MAX,d[y][x]+dist[u.root(ny*N+nx)])
                            f2=True
                else:
                    tmp=d[y][x]
                    f=False
                    break
        ans+=tmp
        dist[u.root(p)]=tmp
        y,x=p//N,p%N
        for k in range(4):
            ny,nx=(y+dy[k],x+dx[k])
            if 0<=ny<N and 0<=nx<N and c[ny][nx]==0:
                res0=u.root(p)
                res1=u.root(ny*N+nx)
                u.unite(p,ny*N+nx)
                dist[u.root(p)]=min(dist[res0],dist[res1])
        c[p//N][p%N]=0
    print(ans)

if __name__ == '__main__':
    main()
