#include<bits/stdc++.h>
#define ls rt<<1
#define rs rt<<1|1
#define lson rt<<1,l,M
#define rson rt<<1|1,M+1,r
#define PI acos(-1)
#define MM int M=(l+r)>>1;
#define fu(i,r,t) for(int i=r;i<=t;i++)
#define fd(i,r,t) for(int i=r;i>=t;i--)
#define fh(i,be,e) for(int i=head[be];~i;i=e[i].next)
#define fa(i,V) for(auto i:V)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long
#define endl '\n'
#define lcm(a,b) (a*b)/__gcd(a,b)
#define cp(i,ans) printf("%.if",ans);
#define cpp(i,ans) cout<<setprecision(i)<<fixed<<ans<<endl;
#define ppb pop_back
#define ppf pop_front
#define pb push_back
#define pf push_front
#define pq priority_queue
#define lowbit(x) (x)&(-x)
#define all(V) V.begin(),V.end()
#define ms multiset
#define mod(x) ((x+mo_num)%mo_num)
#define vc vector
#define vct vector<int>
#define out(i) cout<<(i)<<endl;
#define fi first
#define se second
#define fun(i) fu(i,1,n)
#define fut(i) fu(i,1,t)
#define fum(i) fu(i,1,m)
#define ld long double
#define umap unordered_map
#define P pair<int,int>
#define SET set<int>
#define mp map<int,int>
#define mk make_tuple
#define low lower_bound
#define upp upper_bound
#define yn(key) out(key?"YES":"NO")
#define in(i) i+1,i+1+n
#define im(i) i+1,i+1+m
#define bffs(i) __builtin_ffs(i)
#define bcount(i) __builtin_popcount(i)
#define bone(i) ((1<<i)-1)
#define got(container,num) get<num-1>(container)
using namespace std;
const int INF=LLONG_MAX/2;
const int dx[]={0,0,-1,1},dy[]={-1,1,0,0};//up down left right
const int maxn=1e6+1e5;
const int mo_num=1e9+7;
int n,m,t,a[maxn],b[maxn],ans;
const int N=505;
void update(int pos,int val,int *f){ for(int i=pos;i<=n;i+=lowbit(i)) f[i] += val; }

//ÇóºÍA1~Apos
int getsum(int pos,int *f){ int num = 0;for(int i=pos;i;i-=lowbit(i))num += f[i];return num; }
int row[N][N],col[N][N];
int val[N][N],x[maxn],y[maxn];
int cal(int num)
{
    int r=x[num],c=y[num];
    int have=0;
    int q=getsum(c-1,row[r]),w=getsum(n,row[r])-getsum(c,row[r]),e=getsum(r-1,col[c]),R=getsum(n,col[c])-getsum(r,col[c]);
    have=min({q,w,e,R});
    update(c,-1,row[r]);
    update(r,-1,col[c]);
    return have;
}
main()
{
    IOS
    cin>>n;
    fu(i,1,n*n)
    {
        cin>>a[i];
    }
    int cnt=0;
    fun(i)
    {
        fun(j)
        {
            val[i][j]=++cnt;
            x[val[i][j]]=i;
            y[val[i][j]]=j;
            update(j,1,row[i]);
            update(i,1,col[j]);
        }
    }
    fu(i,1,n*n)
    {
        ans+=cal(a[i]);
    }
    out(ans)
    return 0;
}