#include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
const long long LINF = 1LL << 50;
const int NIL = -1;
const int MAX = 10000;
const int mod = 1000000007;
const double pi = 3.141592653589;
int main() {
  int N;
  cin >> N;
  vector<int> p(N * N);
  int a;
  for (int i = 0; i < N * N; i++) {
    cin >> a;
    a--;
    p[i] = a;
  }
  vector<set<int> > sR(N, set<int>()), sC(N, set<int>());
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      sR[i].insert(i * N + j);
      sC[j].insert(i * N + j);
    }
  }
  int ans = 0;
  for (int i = 0; i < N * N; i++) {
    int r = p[i] / N;
    int c = p[i] % N;
    auto itrR = sR[r].lower_bound(p[i]);
    auto itrC = sC[c].lower_bound(p[i]);
    int idxR = distance(sR[r].begin(), itrR);
    int idxC = distance(sC[c].begin(), itrC);
    int idxR2 = sR[r].size() - idxR - 1;
    int idxC2 = sC[c].size() - idxC - 1;
    ans += min({idxR, idxR2, idxC, idxC2});
    sR[r].erase(itrR);
    sC[c].erase(itrC);
  }
  cout << ans << '\n';
}
