#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using P = pair<int, int>;
int n;
vi mn, sitting;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
P f(int x) {
  int r = x / n;
  int c = x % n;
  return P(r, c);
}
int g(int r, int c) { return r * n + c; }
void printall() {
  for (int(r) = 0; (r) < (n); (r)++) {
    for (int(c) = 0; (c) < (n); (c)++) {
      cout << mn[r * n + c] << " ";
    }
    cout << "| ";
    for (int(c) = 0; (c) < (n); (c)++) {
      cout << sitting[r * n + c] << " ";
    }
    cout << endl;
  }
  for (int(i) = 0; (i) < (n); (i)++) cout << "-";
  cout << endl;
  return;
}
void Main() {
  cin >> n;
  mn.resize(n * n);
  sitting.resize(n * n, 1);
  vi p(n * n);
  for (int(i) = 0; (i) < (n * n); (i)++) {
    cin >> p[i];
    p[i]--;
    int rmn = min(n - 1 - f(i).first, f(i).first);
    int cmn = min(n - 1 - f(i).second, f(i).second);
    mn[i] = min(rmn, cmn);
  }
  ll ans = 0;
  for (int(i) = 0; (i) < (n * n); (i)++) {
    ans += mn[p[i]];
    auto [px, py] = f(p[i]);
    for (int(k) = 0; (k) < (4); (k)++) {
      auto [nx, ny] = P(px + dx[k], py + dy[k]);
      if (nx < 0 || nx >= n || ny < 0 || ny >= n) {
        mn[p[i]] = 0;
        break;
      }
      int next = g(nx, ny);
      mn[p[i]] = min(mn[p[i]], mn[next] + sitting[next]);
    }
    sitting[p[i]] = 0;
    queue<int> q;
    q.push(p[i]);
    while (!q.empty()) {
      auto now = q.front();
      q.pop();
      auto [px, py] = f(now);
      for (int(k) = 0; (k) < (4); (k)++) {
        auto [nx, ny] = P(px + dx[k], py + dy[k]);
        if (nx < 0 || nx >= n || ny < 0 || ny >= n) {
          continue;
        }
        int next = g(nx, ny);
        if (mn[next] > mn[now] + sitting[now]) {
          mn[next] = mn[now];
          q.push(next);
        }
      }
    }
  }
  cout << ans << endl;
  return;
}
int main() {
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(15);
  Main();
  return 0;
}
