#include <bits/stdc++.h>
using namespace std;
int n;
struct position {
  int thisposition;
  int totheend;
};
position a[600][600];
int goaperson(int num, int result) {
  int m = (num - 1) / n;
  int f = (num - 1) - n * m;
  result += a[m][f].totheend;
  a[m][f].thisposition = 0;
  for (int times = 0; times <= 20; times++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        if (i == 0 || i == n - 1 || j == 0 || j == n - 1) a[i][j].totheend = 0;
        if (j != 0 &&
            a[i][j - 1].totheend + a[i][j - 1].thisposition < a[i][j].totheend)
          a[i][j].totheend = a[i][j - 1].totheend + a[i][j - 1].thisposition;
        if (j != n - 1 &&
            a[i][j + 1].totheend + a[i][j + 1].thisposition < a[i][j].totheend)
          a[i][j].totheend = a[i][j + 1].totheend + a[i][j + 1].thisposition;
        if (i != 0 &&
            a[i - 1][j].totheend + a[i - 1][j].thisposition < a[i][j].totheend)
          a[i][j].totheend = a[i - 1][j].totheend + a[i - 1][j].thisposition;
        if (i != n - 1 &&
            a[i + 1][j].totheend + a[i + 1][j].thisposition < a[i][j].totheend)
          a[i][j].totheend = a[i + 1][j].totheend + a[i + 1][j].thisposition;
      }
    }
  }
  return result;
}
int main() {
  int result = 0;
  n = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      a[i][j].thisposition = 1;
      a[i][j].totheend = 99999;
      if (a[i][j].totheend > i) a[i][j].totheend = i;
      if (a[i][j].totheend > n - i - 1) a[i][j].totheend = n - i - 1;
      if (a[i][j].totheend > j) a[i][j].totheend = j;
      if (a[i][j].totheend > n - j - 1) a[i][j].totheend = n - j - 1;
    }
  }
  for (int i = 0; i < n * n; i++) {
    int num;
    scanf("%d", &num);
    result = goaperson(num, result);
    if (result > 1000) {
      printf("-1");
      return 0;
    }
  }
  printf("%d", result);
  return 0;
}
