#include <bits/stdc++.h>
using namespace std;
template <class T>
T maxAny(T a, T b) {
  if (a > b)
    return a;
  else
    return b;
}
template <class T>
T minAny(T a, T b) {
  if (a > b)
    return b;
  else
    return a;
}
int n;
vector<int> lst(250001, 0);
vector<int> mae(250001, 0);
vector<int> usiro(250001, 0);
vector<int> migi(250001, 0);
vector<int> hidari(250001, 0);
vector<bool> notVacant(250001);
void search(int index, int count, int ans, int *depth) {
  if (count > *depth) return;
  int dest = min(min(mae[lst[index]], usiro[lst[index]]),
                 min(migi[lst[index]], hidari[lst[index]]));
  if (dest == 0 && count == 0) {
    *depth = 0;
    return;
  }
  if (dest == 0) return;
  *depth = min(*depth, ans + dest);
  search(index - n, count + 1, ans + notVacant[index], depth);
  search(index + n, count + 1, ans + notVacant[index], depth);
  search(index + 1, count + 1, ans + notVacant[index], depth);
  search(index - 1, count + 1, ans + notVacant[index], depth);
}
int main() {
  long long ans = 0;
  cin >> n;
  lst.resize(n * n + 1);
  for (int i = 0; i < (n * n); i++) cin >> lst[i];
  mae.resize(n * n + 1);
  usiro.resize(n * n + 1);
  migi.resize(n * n + 1);
  hidari.resize(n * n + 1);
  notVacant.resize(n * n + 1);
  for (int i = 1; i <= (n * n); i++) {
    notVacant[i] = true;
    mae[i] = (i - 1) / n;
    usiro[i] = (n - 1) - (i - 1) / n;
    migi[i] = (n - 1) - (i - 1) % n;
    hidari[i] = (i - 1) % n;
  }
  for (int i = 0; i < (n * n); i++) {
    int depth = INT_MAX;
    search(lst[i], 0, 0, &depth);
    ans += depth;
    notVacant[lst[i]] = false;
    for (int j = 1; lst[i] - n * j > 0; j++) {
      usiro[lst[i] - n * j] -= 1;
    }
    for (int j = 1; lst[i] + n * j <= n * n; j++) {
      mae[lst[i] + n * j] -= 1;
    }
    for (int j = 1; (lst[i] - j) % n != 0; j++) {
      migi[lst[i] - j] -= 1;
    }
    for (int j = 1; (lst[i] + j) % n != 1; j++) {
      hidari[lst[i] + j] -= 1;
    }
  }
  cout << ans << endl;
}
