#include <bits/stdc++.h>
using namespace std;
constexpr double PI = 3.1415926535897932;
constexpr double EPS = 1e-9;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
constexpr int dx[4] = {1, 0, -1, 0};
constexpr int dy[4] = {0, 1, 0, -1};
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n;
  std::cin >> n;
  int h = n, w = n;
  int aans = 0;
  vector<vector<char>> s(h, vector<char>(w, '#'));
  std::vector<int> p(n * n);
  for (int i = 0; i < (int)(n * n); i++) {
    std::cin >> p[i];
  }
  for (int iii = 0; iii < n * n; iii++) {
    p[iii]--;
    pair<int, int> st = make_pair(p[iii] / n, p[iii] % n), goal;
    vector<vector<int>> dist(h, vector<int>(w, INF));
    dist[st.first][st.second] = 0;
    deque<pair<int, int>> deq;
    deq.push_back(st);
    while (!deq.empty()) {
      pair<int, int> p = deq.front();
      deq.pop_front();
      int x = p.first, y = p.second;
      for (int i = 0; i < 4; ++i) {
        int nx = x + dx[i], ny = y + dy[i];
        if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
        if (s[nx][ny] == '#') {
          if (dist[nx][ny] > dist[x][y] + 1) {
            dist[nx][ny] = dist[x][y] + 1;
            deq.push_back(pair<int, int>(nx, ny));
          }
        } else {
          if (dist[nx][ny] > dist[x][y]) {
            dist[nx][ny] = dist[x][y];
            if (s[nx][ny] != 'g') deq.push_front(pair<int, int>(nx, ny));
          }
        }
      }
    }
    int ans = INF;
    for (int i = 0; i < (int)(n); i++) {
      ans = min(ans, dist[0][i]);
      ans = min(ans, dist[n - 1][i]);
      ans = min(ans, dist[i][0]);
      ans = min(ans, dist[i][n - 1]);
    }
    aans += ans;
  }
  std::cout << aans << std::endl;
}
