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

template<class T> struct Grid {
    vector<T> data;
    const size_t h, w;
    Grid(size_t h, size_t w, T v = T()) : data(h * w, v), h(h), w(w) {}
    T& operator()(size_t i, size_t j) { return data[i * w + j]; }
    auto adjacent_indexes(size_t i, size_t j) const {
        vector<pair<size_t, size_t>> vs;
        if (i > 0) vs.emplace_back(i - 1, j);
        if (j > 0) vs.emplace_back(i, j - 1);
        if (i + 1 < h) vs.emplace_back(i + 1, j);
        if (j + 1 < w) vs.emplace_back(i, j + 1);
        return vs;
    }
    friend istream& operator>>(istream& in, Grid& g) {
        for (auto& v : g.data) in >> v;
        return in;
    }
    friend ostream& operator<<(ostream& out, const Grid& g) {
        for (size_t i = 0; i < g.h; ++i) {
            cout << g.data[i * g.w];
            for (size_t j = 1; j < g.w; ++j) {
                out << " " << g.data[i * g.w + j];
            }
            out << "\n";
        }
        return out;
    }
};

int main() {
    int n;
    cin >> n;
    Grid<int> g(n, n);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            g(i, j) = min({i, j, n - 1 - i, n - 1 - j});
        }
    }

    int ans = 0;
    for (int i = 0; i < n * n; i++) {
        int p;
        cin >> p;
        int x = (p - 1) / n, y = (p - 1) % n;

        ans += g(x, y);
        queue<pair<size_t, size_t>> q;
        for (auto r : g.adjacent_indexes(x, y)) {
            q.push(r);
        }
        while (!q.empty()) {
            auto [t, u] = q.front(); q.pop();
            if (g(t, u) >= 0) {
                g(t, u) = min(g(t, u), g(x, y));
            } else if (g(t, u) != -p) {
                g(t, u) = -p;
                for (auto [v, w] : g.adjacent_indexes(t, u)) {
                    if (g(v, w) != -p) {
                        q.emplace(v, w);
                    }
                }
            }
        }
        g(x, y) = -p;
    }

    cout << ans << '\n';
}
