from numba import jit

@jit
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)
  for i in range(N*N):
    player=S[i]
    hayasa=P[player]

    que=[[] for _ in range(N)]
    que[0].append(player)
    d[player]=i

    j=0
    finish=0
    while True:
      for kouho in que[j]:
        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[j+1].append(kouho+N)
            d[kouho+N]=i
          else:
            que[j].append(kouho+N)
            d[kouho+N]=i

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

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

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

main()