#include <bits/stdc++.h>
using namespace std;
struct node {
  int l, r, u, d;
  node() { l = r = u = d = -1; }
};
int main() {
  int n;
  cin >> n;
  vector<int> a(n * n);
  for (int i = 0; i < n * n; i++) {
    cin >> a[i];
    a[i]--;
  }
  vector<node> b(n * n);
  for (int i = 0; i < n * n; i++) {
    int x = i / n, y = i % n;
    b[i].l = (y == 0 ? -1 : i - 1);
    b[i].r = (y == n - 1 ? -1 : i + 1);
    b[i].u = (x == 0 ? -1 : i - n);
    b[i].d = (x == n - 1 ? -1 : i + n);
  }
  long long ans = 0;
  for (int i : a) {
    int cl, cr, cu, cd, l = b[i].l, r = b[i].r, u = b[i].u, d = b[i].d;
    cl = cr = cu = cd = 0;
    while (l != -1) {
      cl++;
      l = b[l].l;
    }
    while (r != -1) {
      cr++;
      r = b[r].r;
    }
    while (u != -1) {
      cu++;
      u = b[u].u;
    }
    while (d != -1) {
      cd++;
      d = b[d].d;
    }
    ans += min({cl, cr, cd, cu});
    if (b[i].l != -1) {
      b[b[i].l].r = b[i].r;
    }
    if (b[i].r != -1) {
      b[b[i].r].l = b[i].l;
    }
    if (b[i].u != -1) {
      b[b[i].u].d = b[i].d;
    }
    if (b[i].d != -1) {
      b[b[i].d].u = b[i].u;
    }
  }
  cout << ans << '\n';
}
