#include<bits/stdc++.h>

#define ll long long
#define fornum(A,B,C) for(A=B;A<C;++A)
#define pii pair<int,int>
#define pll pair<ll,ll>

using namespace std;

/////////////////////////////////////////////////////


ll  N, P[1000*1000];


ll mk[1000 * 1000];
ll mk2[1000 * 1000];
ll g[8];
ll i, j, k;
int main(){
    scanf("%lld", &N);
    fornum(i,0,N*N){
        scanf("%lld", &P[i]);
        P[i]--;
    }
    fornum(i,0,N){
        fornum(j,0,N){
            mk[i * N + j] = min(min(i, N - i - 1), min(j, N - j - 1));
        }
    }
    g[0] = 1;
    g[1] = N;
    g[2] = -1;
    g[3] = -N;
    uf.init(N * N + 5);
    ll ans = 0;
    fornum(i,0,N*N){
        //printf("%lld ", P[i]);
        ans += nx[P[i]];
        mk2[P[i]]++;
        queue<ll> q;
        q.push(P[i]);
        while(q.size()){
            ll qa = q.front();
            q.pop();
            fornum(j,0,4){
                ll nx = P[qa] + g[j];
                if(nx<0||N*N<=nx||(qa%N!=nx%N&&qa/N!=nx/N))
                    continue;
                if(mk[qa] + 1 - mk[qa]<mk[nx]){
                    mk[nx] = mk[qa] + 1 - mk[qa];
                    q.push(nx);
                }
            }
        }

    }
    printf("%lld\n", ans);
    return 0;
}