#include <bits/stdc++.h>
using namespace std;
const long long N = 500005;
const long long INF = 0x3f3f3f3f3f3f3f3f;
long long f[N], val[N], vis[N] = {0};
long long n;
long long getf(long long x) {
  if (x == f[x]) return x;
  return f[x] = getf(f[x]);
}
void mergee(long long x, long long y) {
  x = getf(x);
  y = getf(y);
  if (x == y) return;
  f[x] = y;
  val[y] = min(val[x], val[y]);
}
long long id(long long x, long long y) { return (x - 1) * n + y; }
int main() {
  long long p, ans = 0;
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= n; j++) {
      f[id(i, j)] = id(i, j);
      val[id(i, j)] = min(min(j - 1, n - j), min(i - 1, n - i));
    }
  }
  for (long long i = 1; i <= n * n; i++) {
    cin >> p;
    vis[p] = 1;
    if (p % n != 0 && vis[p + 1]) mergee(p, p + 1);
    if (p % n != 1 && vis[p - 1]) mergee(p, p - 1);
    if (p / n != 0)
      if (vis[p - n]) mergee(p, p - n);
    if (p / n != n - 1 && vis[p + n]) mergee(p, p + n);
    ans += val[getf(p)];
  }
  cout << ans << '\n';
  return 0;
}
