#include <bits/stdc++.h>
using ll = long long int;
using P = std::pair<int, int>;
int n;
P conv(int m) { return P((m + n - 1) / n, ((m % n == 0) ? n : m % n)); }
int dis(P p) {
  return std::min({p.first - 1, p.second - 1, n - p.first, n - p.second});
}
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
std::vector<std::vector<P>> pars;
std::vector<std::vector<int>> mindis;
P root(P p) {
  return (pars[p.first][p.second] == p) ? p : root(pars[p.first][p.second]);
}
void unite(P p1, P p2) {
  p1 = root(p1);
  p2 = root(p2);
  if (mindis[p1.first][p1.second] < mindis[p2.first][p2.second])
    pars[p2.first][p2.second] = p1;
  else {
    pars[p1.first][p1.second] = p2;
  }
}
int main() {
  std::cin >> n;
  std::vector<P> a(n * n);
  for (int i = 0; i < n * n; ++i) {
    int m;
    std::cin >> m;
    a[i] = conv(m);
  }
  pars.resize(n + 1, std::vector<P>(n + 1));
  mindis.resize(n + 1, std::vector<int>(n + 1));
  std::vector<std::vector<bool>> used(n + 1, std::vector<bool>(n + 1));
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      pars[i + 1][j + 1] = P(i + 1, j + 1);
      mindis[i + 1][j + 1] = dis(P(i + 1, j + 1));
    }
  }
  int ans = 0;
  for (int i = 0; i < n * n; ++i) {
    int x, y;
    std::tie(x, y) = a[i];
    for (int j = 0; j < 4; ++j) {
      int nx = x + dx[j], ny = y + dy[j];
      if (nx <= 0 || nx > n || ny < 0 || ny > n || !used[nx][ny]) continue;
      unite(P(nx, ny), P(x, y));
    }
    P r = root(P(x, y));
    ans += mindis[r.first][r.second];
    used[x][y] = 1;
  }
  std::cout << ans << std::endl;
  return 0;
}
