#include <bits/stdc++.h>
#define ll long long int
#define ld long double
#define pb push_back
#define ss second
#define ff first
#define INF 300000000000001
#define ll_max 9000000000000000001
#define mod 1000000007
#define PI 3.14159265358979323846L
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define db(args...) {string _ss = #args; replace(_ss.begin(), _ss.end(), ',' , ' '); stringstream ___s(_ss) ; debug(___s, args);}
using namespace std;
typedef vector<pair<ll,ll> > vll;
typedef vector<pair<int,int> > vii ;
typedef pair<ll,ll> pll;
const ll N = 200001;
const ll M = 21;
struct point {
    ll x, y;
    bool operator == (point b)
    {
        if(this -> x == b.x && this -> y == b.y) return 1;
        return 0;
    }
    bool operator != (point b)
    {
        return !(*this == b);
    }
};

void debug(stringstream &s){}
template <typename T, typename... Args>
void debug(stringstream &s, T a, Args... args)
{
    string word;
    s >> word;
    cout << word << " = " << a << endl;
    debug(s, args...);
}

int main()
{
    fast;
    int _ = 1;
    //cin >> _;
    while(_--)
    {
        ll n, m = 0, x = 0, y = 0, ans = 0;
        cin >> n;
        ll a[n * n + 1], b[n * n + 1];
        for(int i = 1; i <= n * n; i++) cin >> a[i], b[i] = 1;
        vector<int> tree[n * n + 1];
        for(int i = 1; i <= n * n; i++)
        {
            if((i + n - 1)/ n == (i + n - 2) / n && i - 1 > 0)
                tree[i].pb(i - 1);
            else
                tree[i].pb(n * n + 1);
            if((i + n - 1)/ n == (i + n) / n && i + 1 <= n * n)
                tree[i].pb(i + 1);
            else
                tree[i].pb(n * n + 1);
            if(i - n > 0)
                tree[i].pb(i - n);
            else
                tree[i].pb(n * n + 1);
            if(i + n <= n * n)
                tree[i].pb(i + n);
            else
                tree[i].pb(n * n + 1);
        }
        for(int i = 1; i <= n * n; i++)
        {
            x = a[i];
            ll sol = INF;
            set<pair<int,int>> s;
            s.insert({0, x});
            bool v[n * n + 1] = {};
            v[x] = 1;
            while(!s.empty())
            {
                y = s.begin() -> first;
                x = s.begin() -> second;
                s.erase(s.begin());
                for(auto j:tree[x])
                {
                    if(j == n * n + 1)
                    {
                        sol = min(y, sol);
                        continue;
                    }
                    if(!v[j])
                    {
                        v[j] = 1;
                        s.insert({y + b[j], j});
                    }
                }
            }
            ans += sol;
            b[a[i]] = 0;
        }
        cout << ans << endl;
     }
    return 0;
}
