#include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
inline bool chmax(A &a, B b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <typename A, typename B>
inline bool chmin(A &a, B b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
using ll = long long;
using pii = pair<int, int>;
constexpr ll INF = 1ll << 30;
constexpr ll longINF = 1ll << 60;
constexpr ll MOD = 1000000007;
constexpr bool debug = 0;
int main() {
  int N;
  cin >> N;
  vector<int> P(N * N);
  for (int i = (0); i < (N * N); ++i) scanf("%d", &P[i]), --P[i];
  vector<vector<vector<int>>> mind(4, vector<vector<int>>(N, vector<int>(N)));
  for (int i = (0); i < (N); ++i)
    for (int j = (0); j < (N); ++j) mind[0][i][j] = i;
  for (int j = (0); j < (N); ++j)
    for (int i = (0); i < (N); ++i) mind[1][i][N - 1 - j] = j;
  for (int i = (0); i < (N); ++i)
    for (int j = (0); j < (N); ++j) mind[2][N - 1 - i][j] = i;
  for (int j = (0); j < (N); ++j)
    for (int i = (0); i < (N); ++i) mind[3][i][j] = j;
  vector<vector<int>> done(N, vector<int>(N));
  int ans = 0;
  for (int t = (0); t < (N * N); ++t) {
    int y = P[t] / N;
    int x = P[t] % N;
    int cur = INF;
    done[y][x] = true;
    {
      int c = 0;
      for (int i = y; i >= 0; --i) {
        if (!done[i][x]) ++c;
        for (int k = (0); k < (4); ++k) chmin(cur, c + mind[k][i][x]);
      }
    }
    {
      int c = 0;
      for (int i = y; i < N; ++i) {
        if (!done[i][x]) ++c;
        for (int k = (0); k < (4); ++k) chmin(cur, c + mind[k][i][x]);
      }
    }
    {
      int c = 0;
      for (int j = x; j < N; ++j) {
        if (!done[y][j]) ++c;
        for (int k = (0); k < (4); ++k) chmin(cur, c + mind[k][y][j]);
      }
    }
    {
      int c = 0;
      for (int j = x; j >= 0; --j) {
        if (!done[y][j]) ++c;
        for (int k = (0); k < (4); ++k) chmin(cur, c + mind[k][y][j]);
      }
    }
    for (int k = (0); k < (4); ++k) chmin(mind[k][y][x], cur);
    for (int i = y + 1, c = 0; i < N; ++i) {
      if (!done[i][x]) ++c;
      chmin(mind[0][i][x], c + cur);
    }
    for (int i = y - 1, c = 0; i >= 0; --i) {
      if (!done[i][x]) ++c;
      chmin(mind[2][i][x], c + cur);
    }
    for (int j = x - 1, c = 0; j >= 0; --j) {
      if (!done[y][j]) ++c;
      chmin(mind[1][y][j], c + cur);
    }
    for (int j = x + 1, c = 0; j < N; ++j) {
      if (!done[y][j]) ++c;
      chmin(mind[3][y][j], c + cur);
    }
    ans += cur;
  }
  cout << ans << endl;
  return 0;
}
