#include <bits/stdc++.h>
using namespace std;
vector<int> Dist;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
class UnionFind {
 public:
  vector<int> Root;
  UnionFind(int N) : Root(N) {
    for (int i = 0; i < N; i++) Root[i] = i;
  }
  int Find(int N) { return (N == Root[N] ? N : Root[N] = Find(Root[N])); }
  bool Same(int X, int Y) { return Find(X) == Find(Y); }
  void Union(int X, int Y) {
    X = Find(X), Y = Find(Y);
    if (X == Y) return;
    if (Dist[X] < Dist[Y])
      Root[Y] = X;
    else
      Root[X] = Y;
  }
};
int main() {
  int N;
  cin >> N;
  vector<int> P(N * N);
  Dist.resize(N * N);
  for (int i = 0; i < N * N; i++) cin >> P[i], P[i]--;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      Dist[i * N + j] = min({i, N - 1 - i, j, N - 1 - j});
    }
  }
  UnionFind UF(N * N);
  vector<vector<bool> > B(N, vector<bool>(N, false));
  long long ANS = 0;
  for (int i = 0; i < N * N; i++) {
    int X = P[i] / N, Y = P[i] % N;
    for (int j = 0; j < 4; j++) {
      int NX = X + dx[j], NY = Y + dy[j];
      if (0 <= NX && NX < N && 0 <= NY && NY < N) {
        if (B[NX][NY]) {
          UF.Union(P[i], NX * N + NY);
        }
      }
    }
    ANS += Dist[UF.Find(P[i])];
    B[X][Y] = true;
  }
  cout << ANS << endl;
}
