#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;


typedef long long ll;
typedef pair<int, int> pii;
#define FOR(i, n) for(int (i)=0; (i)<(n); (i)++)
#define FOR1(i, n) for(int (i)=1; (i)<=(n); (i)++)
#define FORI(i, n) for(int (i)=n-1; (i)>=0; (i)--)

int main(int argc, char** argv) {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << setprecision(15);
    if (argc == 2 && atoi(argv[1]) == 123456789) freopen("d:\\code\\cpp\\contests\\stdin", "r", stdin);

    int n;
    cin >> n;
    int n2 = n*n;
    vector<int> p(n2);
    FOR(i, n2) cin >> p[i];


    vector<oset<int>> rows(n+1);
    vector<oset<int>> cols(n+1);
    FOR1(i, n){
        for(int x = (i-1)*n+1; x <= i*n; x++ )
            rows[i].insert(x);
    }
    FOR1(i, n){
        for(int x = i; x<=n2; x+=n)
            cols[i].insert(x);
    }

    ll sol = 0;
    FOR(i, n2){
        int key = p[i];
        int row = (key-1)/n + 1;
        int col = (key-1)%n + 1;

        int pr = rows[row].order_of_key(key);
        int left = pr;
        int right = rows[row].size()-1 - pr;
        int pc = cols[col].order_of_key(key);
        int up = pc;
        int down = cols[col].size()-1 - pc;

        rows[row].erase(key);
        cols[col].erase(key);

        int nb = min( min(left, right), min(up, down));
        sol += nb;
    }
    cout << sol << endl;

    if (argc == 2 && atoi(argv[1]) == 123456789) cout << clock()*1.0/CLOCKS_PER_SEC << " sec\n";
    return 0;
}