#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int p[n][n];
  for (int i = 0; i < n * n; i++) {
    int x;
    cin >> x;
    x--;
    p[x / n][x % n] = i + 1;
  }
  int ans[n][n];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) ans[i][j] = 1 << 30;
  int bit[n * n + 2];
  for (int i = 0; i < n; i++) {
    memset(bit, 0, sizeof bit);
    for (int j = 0; j < n; j++) {
      int x = p[i][j];
      int c = 0;
      for (int k = x; k <= n * n; k += k & -k) c += bit[k];
      ans[i][j] = min(ans[i][j], c);
      for (int k = x; k > 0; k -= k & -k) bit[k]++;
    }
  }
  for (int i = 0; i < n; i++) {
    memset(bit, 0, sizeof bit);
    for (int j = n - 1; j >= 0; j--) {
      int x = p[i][j];
      int c = 0;
      for (int k = x; k <= n * n; k += k & -k) c += bit[k];
      ans[i][j] = min(ans[i][j], c);
      for (int k = x; k > 0; k -= k & -k) bit[k]++;
    }
  }
  for (int j = 0; j < n; j++) {
    memset(bit, 0, sizeof bit);
    for (int i = 0; i < n; i++) {
      int x = p[i][j];
      int c = 0;
      for (int k = x; k <= n * n; k += k & -k) c += bit[k];
      ans[i][j] = min(ans[i][j], c);
      for (int k = x; k > 0; k -= k & -k) bit[k]++;
    }
  }
  for (int j = 0; j < n; j++) {
    memset(bit, 0, sizeof bit);
    for (int i = n - 1; i >= 0; i--) {
      int x = p[i][j];
      int c = 0;
      for (int k = x; k <= n * n; k += k & -k) c += bit[k];
      ans[i][j] = min(ans[i][j], c);
      for (int k = x; k > 0; k -= k & -k) bit[k]++;
    }
  }
  int sum = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) sum += ans[i][j];
  cout << sum << endl;
}
