#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for (ll i=(a);i<(b);i++)
#define INF 1000000000
#define INF2 10000000000000
using ll =long long;
#define fi first
#define se second
#define mp make_pair
ll graph[510][510][510][510];

ll dijkstra(ll s,ll t,ll N)
    {
        ll cnt=INF;
        vector<vector<ll>> dis(N+2,vector<ll> (N+2,INF2));
        dis[s][t]=0;
        priority_queue<pair<ll,pair<ll,ll>>,vector<pair<ll,pair<ll,ll>>>,greater<pair<ll,pair<ll,ll>>>> que;
        que.push(mp(dis[s][t],mp(s,t)));
        ll u,v;
        while (!que.empty())
        {
            u=que.top().se.fi;
            v=que.top().se.se;
            que.pop();
            vector<pair<ll,ll>> around={mp(u-1,v),mp(u+1,v),mp(u,v+1),mp(u,v-1)};
            ll x,y;
            for (ll i=0;i<4;i++)
            {
                x=around[i].fi;
                y=around[i].se;
                if (dis[x][y]>dis[u][v]+graph[u][v][x][y])
                {
                    dis[x][y]=dis[u][v]+graph[u][v][x][y];
                    //cout << dis[x][y] << " " << x <<y<< endl;
                    if (1<=x &&x<=N && 1<= y&&y <=N) que.push(mp(dis[x][y],mp(x,y)));
                    else
                    {
                        cnt=min(cnt,dis[x][y]/INF);
                    }
                }
            } 
        }
        return cnt;
    }
int main()
{
    ll N;cin >> N;
    FOR(i,0,N+2) FOR(j,0,N+2) FOR(k,0,N+2) FOR(l,0,N+2) graph[i][j][k][l]=INF;
    FOR(i,1,N+1)
    {
        graph[0][i][1][i]=0;
        graph[1][i][0][i]=0;
        graph[N][i][N+1][i]=0;
        graph[N+1][i][N][i]=0;
        graph[i][0][i][1]=0;
        graph[i][1][i][0]=0;
        graph[i][N][i][N+1]=0;
        graph[i][N+1][i][N]=0;
    }
    vector<ll> line(N*N);
    for (ll i=0;i<N*N;i++)
    {
        cin >> line[i];
    }
    ll ans=0;
    for (ll i=0;i<N*N;i++)
    {
        ll s,t;
        s=(line[i]-1)/N+1;
        t=line[i]%N;
        //cout << s << t<< endl;
        ans+=dijkstra(s,t,N);
        graph[s][t-1][s][t]=0;
        graph[s][t+1][s][t]=0;
        graph[s+1][t][s][t]=0;
        graph[s-1][t][s][t]=0;
    }
    cout << ans << endl;
    return 0;
}