#include <bits/stdc++.h>
using namespace std;
using LL = int32_t;
using ULL = int64_t;
using P = pair<LL, LL>;
LL n;
vector<LL> inuse;
bool is_on_edge(LL id) {
  return (id < n) || (id % n == 0) || (id % n == n - 1) || (id >= n * (n - 1));
}
LL costcost(LL id) {
  if (is_on_edge(id)) {
    return 0;
  }
  priority_queue<P, vector<P>, greater<P>> q;
  vector<bool> completed(n * n, false);
  vector<LL> c(n * n, n * n + 500);
  q.push(make_pair((LL)0, id));
  while (!q.empty()) {
    const LL cost = q.top().first;
    const LL ii = q.top().second;
    q.pop();
    if (completed.at(ii)) continue;
    c.at(ii) = cost;
    completed.at(ii) = true;
    if (ii >= n) {
      if (!completed[ii - n]) q.push(make_pair(cost + inuse[ii - n], ii - n));
    }
    if (ii % n != 0) {
      if (!completed[ii - 1]) q.push(make_pair(cost + inuse[ii - 1], ii - 1));
    }
    if (ii % n != n - 1) {
      if (!completed[ii + 1]) q.push(make_pair(cost + inuse[ii + 1], ii + 1));
    }
    if (ii < n * (n - 1)) {
      if (!completed[ii + n]) q.push(make_pair(cost + inuse[ii + n], ii + n));
    }
  }
  LL min_cost = 999999999LL;
  for (int i = 1; i <= n - 2; ++i) {
    if (c.at(i) < min_cost) min_cost = c.at(i);
  }
  for (int i = n * (n - 1); i <= n * n - 1; ++i) {
    if (c.at(i) < min_cost) min_cost = c.at(i);
  }
  for (int i = n; i <= n * (n - 2); i += n) {
    if (c.at(i) < min_cost) min_cost = c.at(i);
  }
  for (int i = n * 2 - 1; i <= n * (n - 1) - 1; i += n) {
    if (c.at(i) < min_cost) min_cost = c.at(i);
  }
  return min_cost;
}
int main() {
  cin >> n;
  vector<LL> p(n * n);
  for (LL i = 0; i < (n * n); ++i) {
    cin >> p.at(i);
    p.at(i) -= 1;
  }
  if (n <= 2) {
    cout << 0 << endl;
    return 0;
  }
  inuse.assign(n * n, 1);
  LL sum = 0;
  for (LL i = 0; i < (n * n); ++i) {
    sum += costcost(p.at(i));
    inuse.at(p.at(i)) = 0;
  }
  cout << sum << endl;
  return 0;
}
