#include <bits/stdc++.h>
int upll(const void* a, const void* b) {
  return *(long long*)a < *(long long*)b   ? -1
         : *(long long*)a > *(long long*)b ? 1
                                           : 0;
}
int downll(const void* a, const void* b) {
  return *(long long*)a < *(long long*)b   ? 1
         : *(long long*)a > *(long long*)b ? -1
                                           : 0;
}
void sortup(long long* a, int n) { qsort(a, n, sizeof(long long), upll); }
void sortdown(long long* a, int n) { qsort(a, n, sizeof(long long), downll); }
long long pom(long long a, long long n, int m) {
  long long x = 1;
  for (a %= m; n; n /= 2) n& 1 ? x = x * a % m : 0, a = a * a % m;
  return x;
}
int unicnt[(1 << 18) + 10];
void ufinit(int n) {
  for (long long i = (0); i < (n); i++) unicnt[i] = 1;
}
int ufroot(int x) {
  return unicnt[x] <= 0 ? -(unicnt[x] = -ufroot(-unicnt[x])) : x;
}
int ufsame(int x, int y) { return ufroot(x) == ufroot(y); }
void uni(int x, int y) {
  if ((x = ufroot(x)) == (y = ufroot(y))) return;
  if (unicnt[x] < unicnt[y]) {
    int t = x;
    x = y;
    y = t;
  }
  unicnt[x] += unicnt[y];
  unicnt[y] = -x;
}
int a[500 * 500 + 10];
int ans[500 * 500 + 10];
int flag[510][510];
void uniuni(int p, int q) {
  int temp = ((ans[ufroot(p)]) < (ans[ufroot(q)]) ? (ans[ufroot(p)])
                                                  : (ans[ufroot(q)]));
  uni(p, q);
  ans[ufroot(p)] = temp;
}
int main() {
  int n;
  scanf("%d", &n);
  for (long long i = (0); i < (n * n); i++) scanf("%d", a + i), a[i]--;
  for (long long i = (0); i < (n); i++)
    for (long long j = (0); j < (n); j++)
      ans[i * n + j] = ((((i) < (n - 1 - i) ? (i) : (n - 1 - i))) <
                                (((j) < (n - 1 - j) ? (j) : (n - 1 - j)))
                            ? (((i) < (n - 1 - i) ? (i) : (n - 1 - i)))
                            : (((j) < (n - 1 - j) ? (j) : (n - 1 - j))));
  ufinit(n * n);
  long long aaaaa = 0;
  for (long long i = (0); i < (n * n); i++) {
    int x = a[i] / n;
    int y = a[i] % n;
    if (x != 0 && flag[x - 1][y]) uniuni(a[i], a[i] - n);
    if (x != n - 1 && flag[x + 1][y]) uniuni(a[i], a[i] + n);
    if (y != 0 && flag[x][y - 1]) uniuni(a[i], a[i] - 1);
    if (y != n - 1 && flag[x][y + 1]) uniuni(a[i], a[i] + 1);
    flag[x][y] = 1;
    aaaaa += ans[ufroot(a[i])];
  }
  printf("%lld", aaaaa);
}
