#include <bits/stdc++.h>
using namespace std;
const int MAX = 510;
const int MOD = 1000000007;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
long long d[MAX][MAX];
bool maze[MAX][MAX];
void dfs(long long x, long long y) {
  long long z = d[x][y] + maze[x][y];
  for (long long i = 0; i < 4; i++) {
    long long nx = x + dx[i];
    long long ny = y + dy[i];
    if (nx < 0 or ny < 0) continue;
    if (d[nx][ny] > z) {
      d[nx][ny] = z;
      dfs(nx, ny);
    }
  }
}
int main() {
  long long N;
  cin >> N;
  long long ans = 0;
  for (long long i = 0; i < N; i++)
    for (long long j = 0; j < N; j++)
      d[i][j] = min(min(i, j), min(N - i - 1, N - j - 1));
  vector<long long> p(N * N);
  for (long long i = 0; i < N * N; i++) cin >> p[i];
  for (long long i = 0; i < N * N; i++) p[i]--;
  for (long long i = 0; i < N; i++) {
    for (long long j = 0; j < N; j++) {
      cout << d[i][j] << " ";
    }
    cout << endl;
  }
  for (long long i = 0; i < MAX; i++)
    for (long long j = 0; j < MAX; j++) maze[i][j] = true;
  for (long long i = 0; i < N * N; i++) {
    long long x = p[i] / N;
    long long y = p[i] % N;
    ans += d[x][y];
    maze[x][y] = false;
    dfs(x, y);
  }
  cout << ans << endl;
}
