#include<bits/stdc++.h>
using namespace std;
using ll=long long;
#define fr(i,n) for(int i=0;i<(n);++i)
#define Fr(i,n) for(int i=1;i<=(n);++i)
#define ifr(i,n) for(int i=(n)-1;i>=0;--i)
#define iFr(i,n) for(int i=(n);i>0;--i)

int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  ll n;
  cin>>n;
  ll arr[n*n] ={0};
  ll enpty[n*n] ={0};
  fr(i,n*n){
    arr[i] = min({i/n,i%n,n-i/n-1,n-i%n-1});
  }
  ll ans,k;
  ans=0;
  queue<ll> que;
  fr(i,n*n){
    ll b;
    cin>>b;
    --b;
    ans += arr[b];
    enpty[b] = 1;
    que.push(b);
    while (!que.empty()) {
    k = que.front();
    if(k/n>0){
      if(arr[k-n] > arr[k]-enpty[k]+1 and arr[k-n]>0){
      arr[k-n]=arr[k]-enpty[k]*1;
      que.push(k-n);
    }}
    if(k%n>0){
      if (arr[k-1] > arr[k]-enpty[k]+1 and arr[k-1]>0){
      arr[k-1]=arr[k]-enpty[k]+1;
      que.push(k-1);
    }}
    if(k/n<n){
      if(arr[k+n] > arr[k]-enpty[k]+1 and arr[k+n]>0){
      arr[k+n]=arr[k]-enpty[k]+1;
      que.push(k+n);
    }}
    if(k%n<n){
      if(arr[k+1]> arr[k]-enpty[k]+1 and arr[k+1]>0){
      arr[k+1]=arr[k]-enpty[k]+1;
      que.push(k+1);
    }}
    que.pop();
  }
  }
  cout<<ans;
}