#include <bits/stdc++.h>

using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define MIN(a,b) ((a)>(b)? (b): (a))
#define MAX(a,b) ((a)<(b)? (b): (a))

const long long INF = 1LL << 60;
typedef unsigned long long ll;
const long long MOD = 1000000000 + 7;

int main(){
    int n;
    cin >> n;
    int p[n*n];
    vector<int> tate[n+1],yoko[n+1];
    rep(i,n){
        rep(j,n){
            cin >> p[n*i+j];
            yoko[i+1].push_back(n*i+j+1);
            tate[j+1].push_back(n*i+j+1);
        }
    }
    ll hate = 0;

    bool seen_ini[n+1][n+1];
    rep(i,n+1) rep(j,n+1) seen_ini[i][j] = true; 
    rep(i,n*n){
        // 4つのどの方角が少ないか計算
        int lef,rig,up,dow;
        int hor,ver;
        queue<pair<pair<int,int>,pair<int,int>>> que;
        hor = (p[i]-1)/n+1;
        ver = p[i]%n;
        if(ver == 0) ver = n;
        que.push({{ver,hor},{0,p[i]}});
        bool finish = false;
        int seen[n+1][n+1] = {0};
        while(!finish){
            pair<pair<int,int>,pair<int,int>> np = que.front();
            que.pop();
            int h = np.first.second;
            int v = np.first.first;
            int num = np.second.first;
            int p = np.second.second;
            auto nh = find(yoko[h].begin(),yoko[h].end(),p);
            auto nv = find(tate[v].begin(),tate[v].end(),p);
            seen[v][h] = 1;
            if( nh == yoko[h].begin() || nv == tate[v].begin() ){
                finish = true;
                hate += num;
                continue;
            }
            if(seen[v-1][h] == 0){
                nv--;
                que.push({{v,h-1},{num+1,*nv}});
                nv++;
            }
            if(seen[v][h-1] == 0){
                nh--;
                que.push({{v-1,h},{num+1,*nh}});
                nh++;
            }
            nv++;
            nh++;        
            if( nh == yoko[h].end() || nv == tate[v].end() ){
                finish = true;
                hate += num;
                continue;
            }
    
            if(seen[v+1][h] == 0){
                que.push({{v,h+1},{num+1,*nv}});
            }
            if(seen[v][h+1] == 0){
                que.push({{v+1,h},{num+1,*nh}});
            }
        }
        yoko[hor].erase(find(yoko[hor].begin(),yoko[hor].end(),p[i]));
        tate[ver].erase(find(tate[ver].begin(),tate[ver].end(),p[i]));
    }
    cout << hate << endl;

    return 0;
}