#include <bits/stdc++.h>
using namespace std;
inline bool OnEdge(int i, int n) {
  return i % n == 1 || i % n == 0 || i <= n || i > (n * n - n);
}
bool OnFakeEdge(int i, const vector<bool> &has_left, int n) {
  auto isOnEdge = OnEdge(i, n) || has_left[i - 1] || has_left[i + 1] ||
                  has_left[i + n] || has_left[i - n];
  return isOnEdge;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  vector<int> perm(n * n);
  for (auto &x : perm) cin >> x;
  vector<bool> has_left(n * n + 1, false);
  int ans = 0;
  for (const auto &x : perm) {
    queue<pair<int, int>> q;
    vector<bool> inserted(n * n + 1);
    q.push(make_pair(x, 0));
    int tans = n;
    while (!q.empty()) {
      const auto p = q.front();
      q.pop();
      if (OnEdge(p.first, n)) {
        tans = min(tans, p.second);
      } else {
        !inserted[p.first - 1]
            ? q.push(make_pair(p.first - 1, p.second + !has_left[p.first - 1]))
            : (void)42;
        !inserted[p.first + 1]
            ? q.push(make_pair(p.first + 1, p.second + !has_left[p.first + 1]))
            : (void)42;
        !inserted[p.first - n]
            ? q.push(make_pair(p.first - n, p.second + !has_left[p.first - n]))
            : (void)42;
        !inserted[p.first + n]
            ? q.push(make_pair(p.first + n, p.second + !has_left[p.first + n]))
            : (void)42;
        inserted[p.first - 1] = inserted[p.first + 1] = inserted[p.first - n] =
            inserted[p.first + n] = true;
      }
    }
    ans += tans;
    has_left[x] = true;
  }
  cout << ans << "\n";
}
