#include<bits/stdc++.h>
using namespace std;
#define ref(i,n) for(int i=1;i<=n;i++)
int b[250001],n,c[250001],used[250001];
vector<int> a[250001];

int main()
{
    cin>>n;
    int nn=pow(n,2);

    ref(i,nn) {

        if(i>=n+1)a[i].push_back(i-n);
        if(i+n<=nn)a[i].push_back(i+n);
        if((i-1)%n)a[i].push_back(i-1);
        if(i%n)a[i].push_back(i+1);
        int u=(i-1)%n,v=(i-1)/n;
        c[i]=min(min(u,n-1-u),min(v,n-1-v));

    }
    int ans=0;
    ref(i,nn){
        int y;
        cin>>y;
        ans+=c[y];




        used[y]=1;

        sort(a[y].begin(),a[y].end());

        ref(j,a[y].size()-1)
            if (a[y][j-1]==a[y][j]) {a[y].erase(a[y].begin()+j-1);j--;}


        ref(j,a[y].size()){
            ref(k,a[y].size())
                if(a[y][j-1]!=a[y][k-1]) a[a[y][j-1]].push_back(a[y][k-1]);

        }

        queue<int> q;
        q.push(y);
        while(q.size()){
            int x=q.front();
            q.pop();
            if(used[x])
                ref(i,a[x].size()){
                    if(!used[a[x][i-1]]&&c[a[x][i-1]]>c[x]) {
                        c[a[x][i-1]]=c[x];
                    q.push(a[x][i-1]);
                }
            }
            else ref(i,a[x].size()){
                if(!used[a[x][i-1]]&&c[a[x][i-1]]>c[x]+1) {
                    c[a[x][i-1]]=c[x]+1;
                    q.push(a[x][i-1]);
                }
            }
        }
    }
    cout<<ans;
    return 0;
}
