#include <bits/stdc++.h>
using namespace std;
using ll = int;
using ld = long double;
using pll = pair<ll, ll>;
using vll = vector<ll>;
using vpll = vector<pll>;
using gr = vector<vll>;
using wgr = vector<vpll>;
struct d_ {
  template <typename T>
  d_& operator,(const T& x) {
    cerr << ' ' << x;
    return *this;
  }
  template <typename T>
  d_& operator,(const vector<T>& x) {
    for (auto x : x) cerr << ' ' << x;
    return *this;
  }
} d_t;
const ll M = 507;
const ll MX = M * M;
ll n;
bool valid(ll first, ll second) {
  return first >= 0 && second >= 0 && first < n && second < n;
}
set<pll> isl[M];
ll uf[MX];
bool isisl[MX];
ll dst[MX];
void init() {
  for (ll i(0); i < MX; i++) uf[i] = i;
}
int find(int e) { return uf[e] == e ? e : uf[e] = find(uf[e]); }
void mrg(int i, int j) {
  if (rand() % 2)
    uf[find(i)] = find(j);
  else if (rand() % 2)
    uf[find(j)] = find(i);
}
ll closestIsland(ll first, ll second) {
  ll dist = min(min(first, n - first - 1), min(second, n - second - 1));
  ll disl = -1;
  for (ll i(max(0, first - n / 4)); i < min(n, first + n / 4); i++) {
    if (!isl[i].size()) continue;
    auto f = [&](ll iy, ll id) {
      id = find(id);
      ll cd = max(0, abs(i - first) - 1) + max(0, abs(iy - second) - 1) +
              +(i != first && iy != second) + dst[id];
      if (dist > cd) {
        dist = cd;
        disl = id;
      }
    };
    auto it = isl[i].lower_bound({second, 0});
    if (it != isl[i].end()) {
      f(it->first, it->second);
    }
    if (it != isl[i].begin()) {
      it--;
      f(it->first, it->second);
    }
  }
  return dist;
}
const ll dx[] = {1, 0, -1, 0};
const ll dy[] = {0, -1, 0, 1};
const ll D = 4;
int main(void) {
  ios_base::sync_with_stdio(false);
  srand(time(0));
  cin >> n;
  ll ret = 0;
  init();
  for (ll i(0); i < n * n; i++) {
    ll p;
    cin >> p;
    p--;
    ll first = p / n, second = p % n;
    ll cur = first * n + second;
    ll cret = closestIsland(first, second);
    ret += cret;
    set<ll> ngisl;
    vpll rowisl;
    for (ll i(0); i < D; i++) {
      ll xx = first + dx[i], yy = second + dy[i];
      if (valid(xx, yy)) {
        ll c = find(xx * n + yy);
        if (isisl[c]) {
          ngisl.insert(c);
        }
      }
    }
    if (ngisl.size()) {
      for (auto i : ngisl) {
        mrg(cur, i);
      }
    }
    cur = find(cur);
    isl[first].insert({second, cur});
    isisl[cur] = 1;
    dst[cur] = cret;
  }
  cout << ret << endl;
  return 0;
}
