#include <bits/stdc++.h>
using namespace std;
inline void logger() { std::cout << " [LOGGER] " << endl; }
template <typename A, typename... B>
void logger(const A& a, const B&... b) {
  cout << a << " , ";
  logger(b...);
}
const long long MOD = 1000000007;
const long long MOD9 = 998244353;
const long long INF = MOD * MOD;
const int MAX = 300005;
struct union_find {
  vector<int> par;
  vector<int> rank;
  vector<int> size;
  vector<int> data;
  union_find(int n) : par(n), rank(n), size(n), data(n) {
    for (int i = 0; i < n; i++) {
      par[i] = i;
      rank[i] = 0;
      size[i] = 1;
    }
  }
  int root(int x) {
    if (par[x] == x) return x;
    par[x] = root(par[x]);
    data[par[x]] = min(data[par[x]], data[x]);
    return par[x];
  }
  void unite(int x, int y) {
    int rx = root(x);
    int ry = root(y);
    if (rx == ry) return;
    if (rank[rx] < rank[ry]) {
      par[rx] = ry;
      data[ry] = min(data[ry], data[rx]);
      size[ry] += size[rx];
    } else {
      par[ry] = rx;
      data[rx] = min(data[rx], data[ry]);
      if (rank[rx] == rank[ry]) rank[rx]++;
      size[rx] += size[ry];
    }
  }
  bool same(int x, int y) {
    int rx = root(x);
    int ry = root(y);
    return rx == ry;
  }
  int getdata(int x) {
    int rx = root(x);
    return data[rx];
  }
};
int main() {
  int n;
  cin >> n;
  vector<vector<int>> vp(n, vector<int>(n));
  vector<int> inv(n * n);
  for (int(k) = 0; (k) < (n * n); (k)++) {
    int p;
    cin >> p;
    p--;
    inv[k] = p;
    vp[p / n][p % n] = k;
  }
  union_find uf(n * n);
  for (int(i) = 0; (i) < (n); (i)++)
    for (int(j) = 0; (j) < (n); (j)++) {
      uf.data[i * n + j] = min({i, n - 1 - i, j, n - 1 - j});
    }
  long long ans = 0;
  vector<pair<long long, long long>> d = {
      pair<long long, long long>(0, 1), pair<long long, long long>(0, -1),
      pair<long long, long long>(1, 0), pair<long long, long long>(-1, 0)};
  for (int(i) = 0; (i) < (n * n); (i)++) {
    int p = inv[i] / n, q = inv[i] % n;
    for (int(k) = 0; (k) < (4); (k)++) {
      int pp = p + d[k].first, qq = q + d[k].second;
      if (pp < 0 || pp >= n || qq < 0 || qq >= n) continue;
      if (vp[pp][qq] < i) {
        uf.unite(inv[i], pp * n + qq);
      }
    }
    ans += uf.getdata(inv[i]);
  }
  cout << (ans) << endl;
}
