#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LLINF = 1e18;
const int maxN = 505;
int BIT_ROW[maxN][maxN];
int BIT_COL[maxN][maxN];
int n;
void updBIT_ROW(int ind, int p, int val = 1) {
  p++;
  for (; p < maxN; p += p & -p) BIT_ROW[ind][p] += val;
}
int sumBIT_ROW(int ind, int p) {
  p++;
  int ret = 0;
  for (; p; p -= p & -p) ret += BIT_ROW[ind][p];
  return ret;
}
void updBIT_COL(int ind, int p, int val = 1) {
  p++;
  for (; p < maxN; p += p & -p) BIT_COL[ind][p] += val;
}
int sumBIT_COL(int ind, int p) {
  p++;
  int ret = 0;
  for (; p; p -= p & -p) ret += BIT_COL[ind][p];
  return ret;
}
int get_row(int x) { return x / n; }
int get_col(int x) { return x % n; }
int A[maxN * maxN];
long long dp[maxN * maxN][4];
long long f(int ind, int choice) {
  if (ind == n * n) return 0;
  if (dp[ind][choice] != -1) return dp[ind][choice];
  long long &ret = dp[ind][choice];
  ret = LLINF;
  int row = get_row(A[ind]), col = get_col(A[ind]);
  if (choice == 0) {
    updBIT_ROW(row, col, -1);
    updBIT_COL(col, row, -1);
    long long aux = sumBIT_COL(col, row);
    for (int i = 0; i < 4; i++) ret = min(ret, aux + f(ind + 1, i));
    updBIT_ROW(row, col);
    updBIT_COL(col, row);
  } else if (choice == 1) {
    updBIT_ROW(row, col, -1);
    updBIT_COL(col, row, -1);
    long long aux = sumBIT_COL(col, n) - sumBIT_COL(col, row);
    for (int i = 0; i < 4; i++) ret = min(ret, aux + f(ind + 1, i));
    updBIT_ROW(row, col);
    updBIT_COL(col, row);
  } else if (choice == 2) {
    updBIT_ROW(row, col, -1);
    updBIT_COL(col, row, -1);
    long long aux = sumBIT_ROW(row, col);
    for (int i = 0; i < 4; i++) ret = min(ret, aux + f(ind + 1, i));
    updBIT_ROW(row, col);
    updBIT_COL(col, row);
  } else {
    updBIT_ROW(row, col, -1);
    updBIT_COL(col, row, -1);
    long long aux = sumBIT_ROW(row, n) - sumBIT_ROW(row, col);
    for (int i = 0; i < 4; i++) ret = min(ret, aux + f(ind + 1, i));
    updBIT_ROW(row, col);
    updBIT_COL(col, row);
  }
  return ret;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      updBIT_COL(j, i);
      updBIT_ROW(i, j);
    }
  }
  for (int i = 0; i < n * n; i++) {
    scanf("%d", &A[i]);
    A[i]--;
  }
  for (int i = 0; i < maxN; i++) {
    dp[i][0] = dp[i][1] = dp[i][2] = dp[i][3] = -1;
  }
  printf("%lld\n", min(min(f(0, 0), f(0, 1)), min(f(0, 2), f(0, 3))));
  return 0;
}
