#include <bits/stdc++.h>
using namespace std;
const int N = 505;
int a[N][N], mn[N][N], t[N * N];
int que(int x) {
  int s = 0;
  for (; x >= 0; x = (x & (x + 1)) - 1) s += t[x];
  return s;
}
void upd(int x, int y) {
  for (; x < N * N; x |= x + 1) t[x] += y;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  for (int i = 0, k = n * n - 1; i < n; i++) {
    for (int j = 0; j < n; j++) {
      int x;
      cin >> x;
      x--;
      a[x / n][x % n] = k--;
      mn[i][j] = N;
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      mn[i][j] = min(mn[i][j], que(a[i][j]));
      upd(a[i][j], 1);
    }
    for (int j = 0; j < n; j++) {
      upd(a[i][j], -1);
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = n - 1; j >= 0; j--) {
      mn[i][j] = min(mn[i][j], que(a[i][j]));
      upd(a[i][j], 1);
    }
    for (int j = 0; j < n; j++) {
      upd(a[i][j], -1);
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      mn[j][i] = min(mn[j][i], que(a[j][i]));
      upd(a[j][i], 1);
    }
    for (int j = 0; j < n; j++) {
      upd(a[j][i], -1);
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = n - 1; j >= 0; j--) {
      mn[j][i] = min(mn[j][i], que(a[j][i]));
      upd(a[j][i], 1);
    }
    for (int j = 0; j < n; j++) {
      upd(a[j][i], -1);
    }
  }
  int ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      ans += mn[i][j];
    }
  }
  cout << ans << "\n";
  return 0;
}
