#include <bits/stdc++.h>
using namespace std;
using pairint = pair<int, int>;
int main(void) {
  int N, Pbuf;
  vector<int> P;
  cin >> N;
  for (int i = 0; i < N * N; i++) {
    cin >> Pbuf;
    Pbuf--;
    P.push_back(Pbuf);
  }
  vector<vector<int>> Graph(N * N);
  vector<bool> Exitable(N * N, false);
  for (int i = 0; i < N * N; i++) {
    if (i % N == 0) {
      Exitable[i] = true;
    } else
      Graph[i].push_back(i - 1);
    if (i % N == N - 1) {
      Exitable[i] = true;
    } else
      Graph[i].push_back(i + 1);
    if (i < N) {
      Exitable[i] = true;
    } else
      Graph[i].push_back(i - N);
    if (i >= N * N - N) {
      Exitable[i] = true;
    } else
      Graph[i].push_back(i + N);
  }
  vector<bool> Occupied(N * N, true);
  int res = 0;
  for (int i = 0; i < N * N; i++) {
    Occupied[P[i]] = false;
    if (Exitable[P[i]]) {
      queue<int> queClear;
      queClear.push(P[i]);
      while (queClear.empty()) {
        int curPoint = queClear.front();
        queClear.pop();
        for (int nxtPoint : Graph[curPoint]) {
          if (Exitable[nxtPoint]) continue;
          Exitable[nxtPoint] = true;
          if (!Occupied[nxtPoint]) queClear.push(nxtPoint);
        }
      }
    } else {
      vector<int> Cost(N * N, -1);
      deque<int> que;
      Cost[P[i]] = 0;
      que.push_front(P[i]);
      int hated = 0;
      bool breakable = false;
      while (!que.empty()) {
        int curPoint = que.front();
        que.pop_front();
        if (Exitable[curPoint]) {
          hated = Cost[curPoint];
          break;
        }
        for (int nxtPoint : Graph[curPoint]) {
          if (Cost[nxtPoint] != -1) continue;
          if (Occupied[nxtPoint]) {
            que.push_back(nxtPoint);
            Cost[nxtPoint] = Cost[curPoint] + 1;
          } else {
            que.push_front(nxtPoint);
            Cost[nxtPoint] = Cost[curPoint];
            if (Exitable[nxtPoint]) {
              hated = Cost[curPoint];
              breakable = true;
              break;
            }
          }
        }
        if (breakable) break;
      }
      res += hated;
    }
  }
  cout << res << endl;
  return 0;
}
