#include <bits/stdc++.h>
using namespace std;
int par[252525];
int dist[252525];
bool vst[252525];
int fnd(int x) { return x == par[x] ? x : par[x] = fnd(par[x]); }
void uni(int x, int y) {
  x = fnd(x), y = fnd(y);
  if (x == y) return;
  par[y] = x;
  dist[x] = min(dist[x], dist[y]);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int n;
  cin >> n;
  int N = n * n;
  for (int i = 0; i < N; ++i) par[i] = i;
  int arr[N];
  for (auto &i : arr) cin >> i, --i;
  for (int i = 0; i < N; ++i) {
    dist[i] = (int)1e9;
    dist[i] = min(dist[i], i % n);
    dist[i] = min(dist[i], n - i % n - 1);
    dist[i] = min(dist[i], i / n);
    dist[i] = min(dist[i], n - i / n - 1);
  }
  long long ans = 0;
  for (auto i : arr) {
    int __ans = dist[i];
    vst[i] = true;
    for (int j = 0; j < 4; ++j) {
      int nx = i / n + "0121"[j] - '1';
      int ny = i % n + "1012"[j] - '1';
      if (nx < 0 || ny < 0 || nx >= n || ny >= n || !vst[nx * n + ny]) continue;
      __ans = min(__ans, dist[fnd(nx * n + ny)]);
    }
    for (int j = 0; j < 4; ++j) {
      int nx = i / n + "0121"[j] - '1';
      int ny = i % n + "1012"[j] - '1';
      if (nx < 0 || ny < 0 || nx >= n || ny >= n || !vst[nx * n + ny]) continue;
      uni(i, nx * n + ny);
    }
    ans += __ans;
  }
  cout << ans;
  return 0;
}
