#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;
    int moov[n+1][n+1] = {0};
    rep(i,n*n){
        // 4つのどの方角が少ないか計算
        int hor,ver;
        queue<pair<pair<int,int>,ll>> que;
        ver = (p[i]-1)/n+1;
        hor = p[i]%n;
        if(hor == 0) hor = n;
        que.push({{ver,hor},0});
        bool finish = false;
        int seen[n+1][n+1] = {0};
        ll min_num = INF;
        while(!que.empty()){
            pair<pair<int,int>,ll> np = que.front();
            que.pop();
            int h = np.first.second;
            int v = np.first.first;
            ll num = np.second;
            if(min_num <= num) continue;
            seen[v][h] = 1;
            if( h == 1 || v == 1 || h == n || v == n){
                finish = true;
                min_num = MIN(min_num,num);
                continue;
            }
            if(seen[v+1][h] == 0){
                if(moov[v+1][h] == 0){
                    que.push({{v+1,h},{num+1}});
                }else{
                    que.push({{v+1,h},{num}});
                }
            }
            if(seen[v][h+1] == 0){
                if(moov[v][h+1] == 0){
                    que.push({{v,h+1},{num+1}});
                }else{
                    que.push({{v,h+1},{num}});
                }
            }
            if(seen[v][h-1] == 0){
                if(moov[v][h-1] == 0){
                    que.push({{v,h-1},{num+1}});
                }else{
                    que.push({{v,h-1},{num}});
                }
            }
            if(seen[v-1][h] == 0){
                if(moov[v-1][h] == 0){
                    que.push({{v-1,h},{num+1}});
                }else{
                    que.push({{v-1,h},{num}});
                }
            }
        }
        moov[ver][hor] = 1;
        hate += min_num;
    }
    cout << hate << endl;

    return 0;
}