#include <bits/stdc++.h>
#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
using ll = long long;
using datas = pair<ll, ll>;
using ddatas = pair<long double, long double>;
using tdata = pair<ll, datas>;
using vec = vector<ll>;
using mat = vector<vec>;
using pvec = vector<datas>;
using pmat = vector<pvec>;
const ll mod = 1000000007;
const ll inf = 1LL << 60;
const long double PI = acos(-1);
const long double eps = 1e-9;
template <class T>
inline bool chmax(T& a, T b) {
  bool x = a < b;
  if (x) a = b;
  return x;
}
template <class T>
inline bool chmin(T& a, T b) {
  bool x = a > b;
  if (x) a = b;
  return x;
}
void startupcpp() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(15);
}
using P = pair<int, int>;
int v[250001], ord[250001];
int main() {
  startupcpp();
  int i, j, k, N, M, ans = 0, res;
  cin >> N;
  M = N * N;
  for (i = 0; i < (ll)M; ++i) {
    cin >> v[i];
    ord[--v[i]] = i;
  }
  vector<bool> dist(M);
  int d[4] = {1, -1, N, -N};
  for (k = 0; k < (ll)M; ++k) {
    dist.assign(M, false);
    deque<P> que;
    que.emplace_back(0, v[k]);
    while (!que.empty()) {
      P x = que.front();
      que.pop_front();
      if (dist[x.second]) continue;
      dist[x.second] = true;
      i = x.second / N;
      j = x.second % N;
      if (i == 0 || j == 0 || i == N - 1 || j == N - 1) {
        res = x.first;
        break;
      }
      for (i = 0; i < (ll)4; ++i)
        if (!dist[x.second + d[i]]) {
          if (ord[x.second + d[i]] > k) {
            que.emplace_back(x.first + 1, x.second + d[i]);
          } else {
            que.emplace_front(x.first, x.second + d[i]);
          }
        }
    }
    ans += res;
  }
  cout << ans << "\n";
}
