#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  vector<vector<int>> l(n + 2, vector<int>(n + 2, 0));
  vector<vector<int>> r(n + 2, vector<int>(n + 2, n + 1));
  vector<vector<int>> u(n + 2, vector<int>(n + 2, 0));
  vector<vector<int>> d(n + 2, vector<int>(n + 2, n + 1));
  int res = 0;
  auto add = [&](int a, int b) -> void {
    for (int j = a; j <= n; j++) u[j][b] = max(u[j][b], a);
    for (int j = 1; j <= a; j++) d[j][b] = min(d[j][b], a);
    for (int j = b; j <= n; j++) l[a][j] = max(l[a][j], b);
    for (int j = 1; j <= b; j++) r[a][j] = min(r[a][j], b);
  };
  for (int i = 0; i < n * n; i++) {
    int p;
    cin >> p;
    int a = (p - 1) / n + 1;
    int b = (p - 1) % n + 1;
    int best = n + 1;
    pair<char, int> dir;
    for (int j = 1; j <= n; j++) {
      if (abs(b - j) + a - u[a][j] < best) {
        best = abs(b - j) + u[a][j] - a;
        dir = {'U', j};
      }
      if (abs(b - j) + d[a][j] - a < best) {
        best = abs(b - j) + d[a][j] - a;
        dir = {'D', j};
      }
      if (abs(a - j) + b - l[j][b] < best) {
        best = abs(a - j) + b - l[j][b];
        dir = {'L', j};
      }
      if (abs(a - j) + r[j][b] - b < best) {
        best = abs(a - j) + r[j][b] - b;
        dir = {'R', j};
      }
    }
    res += best;
    if (dir.first == 'U' || dir.first == 'D') {
      for (int j = b; j <= dir.second; j++) add(a, j);
      for (int j = b; j >= dir.second; j--) add(a, j);
      if (dir.first == 'U')
        for (int j = a; j > a - (best - abs(b - dir.second)); j--)
          add(j, dir.second);
      else
        for (int j = a; j < a + (best - abs(b - dir.second)); j++)
          add(j, dir.second);
    } else {
      for (int j = a; j <= dir.second; j++) add(j, b);
      for (int j = a; j >= dir.second; j--) add(j, b);
      if (dir.first == 'L')
        for (int j = b; j > b - (best - abs(a - dir.second)); j--)
          add(dir.second, j);
      else
        for (int j = b; j < b + (best - abs(a - dir.second)); j++)
          add(dir.second, j);
    }
  }
  cout << res / 2 << "\n";
  return 0;
}
