#include <bits/stdc++.h>
using namespace std;
const int N_MAX = 505;
int F[N_MAX * N_MAX], H[N_MAX * N_MAX], MS[N_MAX * N_MAX];
int N;
int di[] = {0, 1, 0, -1}, dj[] = {1, 0, -1, 0};
bool vis[N_MAX][N_MAX];
bool valid(int i, int j) { return i >= 0 and i < N and j >= 0 and j < N; }
int fth(int x) {
  if (F[x] == x) return x;
  return F[x] = fth(F[x]);
}
void union_find(int x, int y) {
  if (H[x] < H[y]) {
    F[x] = y;
    MS[y] = min(MS[y], MS[x]);
  } else {
    F[y] = x;
    MS[x] = min(MS[x], MS[y]);
    if (H[x] == H[y]) H[x]++;
  }
}
void init() {
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      vis[i][j] = 0;
      H[i * N + j] = 1;
      F[i * N + j] = i * N + j;
      MS[i * N + j] = min(min(i, N - 1 - i), min(j, N - 1 - j));
    }
  }
}
int main() {
  cin >> N;
  queue<int> Q;
  for (int i = 0; i < N * N; i++) {
    int z;
    cin >> z;
    Q.push(z);
  }
  init();
  int ans = 0;
  while (!Q.empty()) {
    int z = Q.front();
    Q.pop();
    int si = (z - 1) / N;
    int sj = (z - 1) % N;
    for (int i = 0; i < 4; i++) {
      int ui = si + di[i];
      int uj = sj + dj[i];
      if (valid(ui, uj)) {
        if (vis[ui][uj]) {
          union_find(fth(z - 1), fth(ui * N + uj));
        }
      }
    }
    vis[si][sj] = 1;
    ans += MS[fth(z - 1)];
  }
  cout << ans << endl;
  return 0;
}
