#include <bits/stdc++.h>
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  } else {
    return false;
  }
}
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}
using namespace std;
int main() {
  int n, ans = 0;
  int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
  cin >> n;
  vector<vector<int>> now(n, vector<int>(n));
  vector<vector<int>> s(n, vector<int>(n, 1));
  for (int i = 0; i < (n); i++)
    for (int j = 0; j < (n); j++) {
      now[i][j] = min({i, j, n - i - 1, n - j - 1});
    }
  for (int i = 0; i < (n * n); i++) {
    int a;
    cin >> a;
    a--;
    int X = a / n, Y = a % n;
    ans += now[X][Y];
    s[X][Y] = 0;
    queue<pair<int, int>> que;
    que.push({X, Y});
    while (!que.empty()) {
      pair<int, int> p = que.front();
      que.pop();
      int x = p.first, y = p.second;
      for (int j = 0; j < (4); j++) {
        int nx = x + dx[j], ny = y + dy[j];
        if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
        if (chmin(now[nx][ny], now[x][y] + s[x][y])) que.push({nx, ny});
      }
    }
    for (int i = 0; i < (n); i++) {
      for (int j = 0; j < (n); j++)
        cout << now[i][j] << (j != n - 1 ? " " : "");
      cout << endl;
    }
    cout << endl;
  }
  cout << ans << endl;
}
