#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
int n;
int maze[500][500];
int check_maze[500][500];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
bool goal = false;
void dfs(int num, int prev_x, int prev_y, int x, int y) {
  if (check_maze[y][x]) return;
  check_maze[y][x] = true;
  maze[y][x] = 0;
  for (int i = 0; i < 4; i++) {
    int nx = x + dx[i];
    int ny = y + dy[i];
    if (nx < 0 || n <= nx || ny < 0 || n <= ny) {
      goal = true;
      return;
    } else if (0 <= nx && nx < n && 0 <= ny && ny < n && maze[ny][nx] == 0 &&
               check_maze[ny][nx] == false) {
      dfs(num, x, y, nx, ny);
    }
  }
}
int main(int argc, const char* argv[]) {
  cin >> n;
  vector<int> order;
  for (int h = 0; h < n; h++) {
    for (int w = 0; w < n; w++) {
      int number;
      cin >> number;
      order.push_back(number);
      maze[h][w] = h * n + w + 1;
      check_maze[h][w] = 100000000;
    }
  }
  int ans = 0;
  for (int i = 0; i < order.size(); i++) {
    int res = 100000000;
    int x = (order[i] - 1) % n;
    int y = (order[i] - 1) / n;
    queue<P> que;
    que.push(P(x, y));
    maze[y][x] = 0;
    check_maze[y][x] = 0;
    while (que.size()) {
      P p = que.front();
      que.pop();
      for (int i = 0; i < 4; i++) {
        int nx = p.first + dx[i];
        int ny = p.second + dy[i];
        if (0 <= nx && nx < n && 0 <= ny && ny < n && maze[ny][nx] == 0 &&
            check_maze[ny][nx] == 100000000) {
          que.push(P(nx, ny));
          check_maze[ny][nx] = check_maze[p.second][p.first];
        } else if (0 <= nx && nx < n && 0 <= ny && ny < n && maze[ny][nx] > 0 &&
                   check_maze[ny][nx] == 100000000) {
          que.push(P(nx, ny));
          check_maze[ny][nx] = check_maze[p.second][p.first] + 1;
        } else if (nx < 0 || n <= nx || ny < 0 || n <= ny) {
          res = min(res, check_maze[p.second][p.first]);
        }
      }
    }
    for (int h = 0; h < n; h++) {
      for (int w = 0; w < n; w++) {
        check_maze[h][w] = 100000000;
      }
    }
    ans += res;
  }
  cout << ans << endl;
  return 0;
}
