#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long INF_LL = 1e18 + 3;
const int INF_int = 1e9 + 3;
int main() {
  int n;
  cin >> n;
  int arr[n * n];
  for (int i = 0; i < n * n; i++) cin >> arr[i];
  vector<int> amari[n];
  vector<int> syou[n];
  long long ans = 0;
  for (int i = 0; i < n * n; i++) {
    int now = arr[i];
    int am = (now - 1) % n;
    int sy = (now - 1) / n;
    int n1 = lower_bound(amari[am].begin(), amari[am].end(), sy) -
             (amari[am].begin());
    int n1_ = (n - 1 - sy) - (amari[am].size() - n1);
    n1 = sy - n1;
    n1 = min(n1, n1_);
    int n2 =
        lower_bound(syou[sy].begin(), syou[sy].end(), am) - (syou[sy].begin());
    int n2_ = (n - 1 - am) - (syou[sy].size() - n2);
    n2 = am - n2;
    n2 = min(n2, n2_);
    amari[am].push_back(sy);
    syou[sy].push_back(am);
    ans += min(n1, n2);
    sort(amari[am].begin(), amari[am].end());
    sort(syou[sy].begin(), syou[sy].end());
  }
  cout << ans << endl;
}
