from collections import deque

def main():
  N=int(input())
  S=list(map(int,input().split()))
  count=0
  P=[0]*(N*N+1)
  for j in range(N*N):
    P[S[j]]=j+1
  d=[-1]*(N*N+1)
  que=deque()
  for i in range(N*N):
    player=S[i]
    hayasa=P[player]
    que.clear()
    que.append((player,0))
    d[player]=i

    finish=-1
    while que:
      kouho,j=que.popleft()
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break

      if d[kouho+N]<i:
        if P[kouho+N]>hayasa:
          que.append((kouho+N,j+1))
          d[kouho+N]=i
        else:
          que.appendleft((kouho+N,j))
          d[kouho+N]=i

      if d[kouho-N]<i:
        if P[kouho-N]>hayasa:
          que.append((kouho-N,j+1))
          d[kouho-N]=i
        else:
          que.appendleft((kouho-N,j))
          d[kouho-N]=i

      if d[kouho+1]<i:
        if P[kouho+1]>hayasa:
          que.append((kouho+1,j+1))
          d[kouho+1]=i
        else:
          que.appendleft((kouho+1,j))
          d[kouho+1]=i

      if d[kouho-1]<i:
        if P[kouho-1]>hayasa:
          que.append((kouho-1,j+1))
          d[kouho-1]=i
        else:
          que.appendleft((kouho-1,j))
          d[kouho-1]=i
    count+=j

  print(count)

main()
