#include <bits/stdc++.h>
using namespace std;
#define ll long long

struct unionfind{
    vector<int> parent;
    vector<int> rank;
    vector<int> size;

    unionfind (int N) {
        parent = vector<int>(N);
        iota(parent.begin(), parent.end(), 0);
        rank = vector<int>(N, 0);
        size = vector<int>(N, 1);
    }
    int root(int x) {
        if (parent[x] == x) return x;
        parent[x] = root(parent[x]);
        return parent[x];
    }
    
    bool same(int x, int y){
        return root(x) == root(y);
    }
    
    void unite(int x, int y){
        x = root(x);
        y = root(y);
        if (x == y) return;
        if (rank[x] > rank[y]) {
            parent[y] = x;
            size[x] += size[y];
        }
        else {
            parent[x] = y;
            size[y] += size[x];
            if (rank[x] == rank[y]) rank[y] += 1;
        }
    }
    
    int getsize(int x) {
        return size[root(x)];
    }
};

int main() {
    int N;
    cin >> N;
    vector<vector<int>> A(N, vector<int>(N, 0));
    for (int i = 0; i < N*N; i++) {
        int P;
        cin >> P;
        P--;
        A[P/N][P%N] = i;
    }
    
    vector<vector<int>> dist(N, vector<int>(dist, 0));
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            dist[i][j] = min(min(i, N-1-i), min(j, N-1-j));
        }
    }
    
    vector<int> dx = {0,0,1,-1}, dy={1,-1,0,0};
    for (int i = 0; i < N; i++) {
        for (int j = 1; j < N-1; j++) {
            for (int k = 1; k < N-1; k++) {
                for (int l = 0; l <= 3; l++) {
                    int nx = j+dx[l], ny = k+dy[l];
                    if (A[j][k] < A[nx][ny]) {
                        dist[j][k] = min(dist[j][k], dist[nx][ny]+1);
                    }else {
                        dist[j][k] = min(dist[j][k], dist[nx][ny]);
                    }
                }
            }
        }
    }
    ll ans = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            ans += dist[i][j];
        }
    }
    cout << ans << endl;
    return 0;
}
