#include <bits/stdc++.h>
using namespace std;
const long long N = 500 + 9;
const long long inf = 1e9 + 7;
long long dx[4] = {1, -1, 0, 0};
long long dy[4] = {0, 0, 1, -1};
long long n, a[N * N], i, lab[N * N], j, minn;
bool chk[N * N];
long long Find(long long u) {
  if (lab[u] < 0) return u;
  return lab[u] = Find(lab[u]);
}
void Union(long long r, long long s) {
  lab[s] = max(lab[s], lab[r]);
  lab[r] = s;
}
bool check(long long x, long long y) {
  return (x <= n && y <= n && x >= 1 && y >= 1);
}
long long trans(long long x, long long y) { return (x - 1) * n + y; }
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  if (fopen("tst"
            ".inp",
            "r")) {
    freopen(
        "tst"
        ".inp",
        "r", stdin);
  }
  cin >> n;
  for (i = 1; i <= n * n; i++) cin >> a[i];
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= n; j++) {
      long long x =
          min(min(abs(i - 1), abs(i - n)), min(abs(j - 1), abs(j - n)));
      lab[trans(i, j)] = -x - 1;
    }
  }
  long long ans = 0;
  for (i = 1; i <= n * n; i++) {
    long long p = a[i];
    minn = -1 * (lab[Find(p)] + 1);
    chk[a[i]] = true;
    long long x = ceil((long double)p / n), y = p - (x - 1) * n;
    for (j = 0; j < 4; j++) {
      long long u = x + dx[j], v = y + dy[j];
      if (check(u, v) && chk[trans(u, v)]) {
        long long r = Find(p), s = Find(trans(u, v));
        if (r != s) Union(r, s);
        minn = min(minn, -1 * (lab[Find(p)] + 1));
      }
    }
    ans += minn;
  }
  cout << ans;
}
