#include <bits/stdc++.h>
using namespace std;
const int N = 555;
int a[N * N], d[N * N], f[N * N];
int vis[N][N];
int n, m, k, tot;
int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};
int find(int x) {
  if (f[x] == x) return x;
  return f[x] = find(f[x]);
}
void hb(int x, int y) {
  int fx = find(x), fy = find(y);
  if (fx != fy) f[fx] = fy, d[fy] = min(d[fy], d[fx]);
}
int put(int s) {
  int x = (s - 1) / n + 1;
  int y = s - (x - 1) * n;
  int ans = d[s];
  vis[x][y] = 1;
  for (int i = 0; i < 4; i++) {
    int p = x + dx[i], q = y + dy[i];
    if (p < 1 || p > n || q < 1 || q > n) continue;
    if (vis[p][q]) {
      int g = d[find((p - 1) * n + q)];
      ans = min(ans, g);
    }
  }
  for (int i = 0; i < 4; i++) {
    int p = x + dx[i], q = y + dy[i];
    if (p < 1 || p > n || q < 1 || q > n) continue;
    if (vis[p][q]) {
      hb((p - 1) * n + q, (x - 1) * n + y);
    }
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
      d[(i - 1) * n + j] = min(min(i - 1, n - i), min(j - 1, n - j));
  for (int i = 1; i <= n * n; i++) scanf("%d", &a[i]), f[i] = i;
  int ans = 0;
  for (int i = 1; i <= n * n; i++) {
    int g = put(a[i]);
    ans = ans + g;
  }
  printf("%d\n", ans);
  return 0;
}
