#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> p(n * n);
  vector<vector<int>> a(n, vector<int>(n));
  for (int i = 0; i < n * n; i++) {
    cin >> p[i];
    p[i]--;
    a[p[i] / n][p[i] % n] = i;
  }
  int cur;
  vector<vector<int>> d;
  int dx[4] = {1, -1, 0, 0};
  int dy[4] = {0, 0, 1, -1};
  function<void(int, int)> bfs = [&](int i, int j) {
    deque<pair<int, int>> que;
    que.emplace_back(i, j);
    while (!que.empty()) {
      tie(i, j) = que.front();
      que.pop_front();
      for (int k = 0; k < 4; k++) {
        int ni = i + dx[k], nj = j + dy[k];
        if (0 <= ni && ni < n && 0 <= nj && nj < n) {
          if (a[ni][nj] < cur) {
            if (d[ni][nj] > d[i][j]) {
              d[ni][nj] = d[i][j];
              que.emplace_front(ni, nj);
            }
          } else {
            if (d[ni][nj] > d[i][j] + 1) {
              d[ni][nj] = d[i][j] + 1;
              que.emplace_back(ni, nj);
            }
          }
        }
      }
    }
  };
  int ans = 0;
  for (int i = 0; i < n * n; i++) {
    cur = i;
    d = vector<vector<int>>(n, vector<int>(n, 1e9));
    d[p[i] / n][p[i] % n] = 0;
    bfs(p[i] / n, p[i] % n);
    int res = 1e9;
    for (int j = 0; j < n; j++) {
      res = min({res, d[0][j], d[n - 1][j], d[j][n - 1], d[j][0]});
    }
    ans += res;
  }
  cout << ans << '\n';
  return 0;
}
