#include <bits/stdc++.h>
using namespace std;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int inside(int x, int y, int N) {
  return (0 <= x && x < N) && (0 <= y && y < N);
}
int main() {
  long long N;
  cin >> N;
  vector<int> p(N * N);
  vector<int> inv(N * N);
  vector<vector<int>> grid(N, vector<int>(N, 0));
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      cin >> p[i * N + j];
      p[i * N + j]--;
      inv[p[i * N + j]] = i * N + j;
      grid[i][j] = i * N + j;
    }
  }
  long long ans = 0;
  for (int k = 0; k < N * N; k++) {
    int val = p[k];
    int i = val / N;
    int j = val % N;
    int cur = N;
    for (int q = 0; q < 4; q++) {
      int ii = i;
      int jj = j;
      int count = 0;
      while (inside(ii + dx[q], jj + dy[q], N)) {
        ii += dx[q];
        jj += dy[q];
        if (inv[grid[ii][jj]] > k) count++;
      }
      cur = min(cur, count);
    }
    ans += cur;
  }
  cout << ans << endl;
}
