#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  long long n;
  cin >> n;
  vector<long long> v(n * n);
  for (auto &i : v) cin >> i;
  vector<vector<long long>> seats(n, vector<long long>(n));
  map<long long, pair<long long, long long>> mp;
  long long seat_no = 1;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < n; j++) {
      mp[seat_no] = {i, j};
      seats[i][j] = seat_no++;
    }
  }
  vector<vector<long long>> movements = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};
  long long total_hating_pairs = 0;
  for (long long i = 0; i < n * n; i++) {
    set<pair<long long, long long>> visited;
    queue<pair<pair<long long, long long>, long long>> q;
    q.push({mp[v[i]], 0});
    long long a = mp[v[i]].first;
    long long b = mp[v[i]].second;
    seats[a][b] = 0;
    visited.insert({a, b});
    long long hating_people = LLONG_MAX;
    while (!q.empty()) {
      pair<long long, long long> curr_pos = q.front().first;
      long long hatred = q.front().second;
      q.pop();
      for (auto m : movements) {
        long long row = curr_pos.first + m[0];
        long long col = curr_pos.second + m[1];
        if (visited.find({row, col}) != visited.end())
          continue;
        else
          visited.insert({row, col});
        if (row >= 0 && row < n && col >= 0 && col < n) {
          if (seats[row][col] == 0)
            q.push({{row, col}, hatred});
          else
            q.push({{row, col}, hatred + 1});
        } else {
          hating_people = min(hating_people, hatred);
        }
      }
    }
    total_hating_pairs += hating_people;
  }
  cout << total_hating_pairs << "\n";
  return 0;
}
