#include <bits/stdc++.h>
#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long int N, A, B, C, D, E, F, M, K, L, X, Y, Z, H, W, sum = 0, num = 0,
                                                             flag = 0;
  string S, T;
  cin >> N;
  long long int d[4] = {-1, 1, N, 0 - N};
  vector<long long int> P(N * N, 0);
  vector<long long int> G(N * N, 0);
  for (long long int i = 0; i < N * N; i++) cin >> P[i];
  for (long long int i = 0; i < N * N; i++) {
    A = i % N;
    B = i / N;
    if (A || B || N - A - 1 || N - B - 1) {
      vector<long long int> dist(N * N, 9999999999);
      deque<int> que;
      dist[P[i] - 1] = 0;
      que.push_back(P[i] - 1);
      while (!que.empty()) {
        auto v = que.front();
        que.pop_front();
        for (long long int i = 0; i < 4; i++) {
          auto nv = v + d[i];
          if (nv < 0 || nv >= N * N) continue;
          if (dist[nv] > dist[v] + 1 && !G[nv]) {
            dist[nv] = dist[v] + 1;
            que.push_back(nv);
          } else if (dist[nv] > dist[v] && G[nv]) {
            dist[nv] = dist[v];
            que.push_front(nv);
          }
        }
      }
      num = 9999999999;
      for (long long int i = 0; i < N; i++)
        num = (((num) > (dist[i])) ? (dist[i]) : (num));
      for (long long int i = 1; i < N - 1; i++)
        num = (((num) > (min(dist[i * N], dist[(i + 1) * N - 1])))
                   ? (min(dist[i * N], dist[(i + 1) * N - 1]))
                   : (num));
      for (long long int i = N * (N - 1); i < N * N; i++)
        num = (((num) > (dist[i])) ? (dist[i]) : (num));
      sum += num;
    }
    G[P[i] - 1] = 1;
  }
  cout << sum << endl;
}
