#include <bits/stdc++.h>
int main() {
  using namespace std;
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  int N;
  cin >> N;
  vector<int> P(N * N), order(N * N);
  for (auto& e : P) cin >> e, --e;
  for (int i = 0; i < N * N; ++i) order[P[i]] = i;
  auto on_edge = [&](int pos) {
    return pos / N == 0 || pos / N == N - 1 || pos % N == 0 || pos % N == N - 1;
  };
  const array<int, 4> kDirs = {{-N, 1, N, -1}};
  constexpr int kInf = INT_MAX;
  int ans = 0;
  for (int i : P) {
    if (on_edge(i)) continue;
    vector<int> record(N * N, kInf);
    deque<int> que;
    que.push_back(i);
    record[i] = 0;
    while (!que.empty()) {
      int cur = que.front();
      que.pop_front();
      for (int dir : kDirs) {
        int nxt = cur + dir;
        bool dislike = order[i] < order[nxt];
        if (record[cur] + dislike < record[nxt]) {
          record[nxt] = record[cur] + dislike;
          if (on_edge(nxt)) continue;
          if (dislike)
            que.push_back(nxt);
          else
            que.push_front(nxt);
        }
      }
    }
    int cost = kInf;
    for (int j = 0; j < N * N; ++j)
      if (on_edge(j)) cost = min(cost, record[j]);
    ans += cost;
  }
  cout << ans << endl;
}
