#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long int N, ans = 0, i, j, k;
  cin >> N;
  bool second[N][N];
  long long int P[N * N];
  for (i = 0; i < N; i++)
    for (j = 0; j < N; j++) {
      second[i][j] = 1;
      cin >> P[i * N + j];
      P[i * N + j]--;
    }
  for (i = 0; i < N * N; i++) {
    long long int D[N][N], ANS = N * N;
    pair<long long int, long long int> s;
    s.first = P[i] / N;
    s.second = P[i] % N;
    queue<pair<long long int, long long int>> X;
    X.push(s);
    for (j = 0; j < N; j++)
      for (k = 0; k < N; k++) D[j][k] = N * N;
    second[s.first][s.second] = 0;
    D[s.first][s.second] = 0;
    long long int A[4] = {1, -1, 0, 0}, B[4] = {0, 0, 1, -1};
    while (X.size()) {
      long long int x = X.front().first, y = X.front().second;
      if (x < N && x >= 0 && y < N && y >= 0)
        for (j = 0; j < 4; j++) {
          long long int a = x + A[j], b = y + B[j];
          if (a < N && b < N && a >= 0 && b >= 0 && D[a][b] > D[x][y] + 1) {
            X.push(pair<long long int, long long int>(a, b));
            D[a][b] = D[x][y];
            if (second[a][b]) D[a][b]++;
          }
        }
      X.pop();
    }
    for (j = 0; j < N; j++)
      ANS = min({ANS, D[0][j], D[j][0], D[N - 1][j], D[j][N - 1]});
    ans += ANS;
  }
  cout << ans << endl;
  return 0;
}
