#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vvl = vector<vl>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
using vpii = vector<pii>;
using vpli = vector<pli>;
using vpll = vector<pll>;
int INF = 1e9 + 7;
int N;
vvi dis;
vector<vector<bool>> check;
vi dx = {-1, 0, 1, 0}, dy = {0, -1, 0, 1};
void dfs(int a, int b) {
  check[a][b] = true;
  int x, y;
  for (int i = 0; i < (int)4; i++) {
    x = a + dx[i], y = b + dy[i];
    if (0 <= x && x < N && 0 <= y && y < N &&
        (dis[x][y] > dis[a][b] + 1 ||
         (dis[a][b] == 0 && dis[x][y] == 1 && check[x][y]))) {
      dis[x][y]--;
      dfs(x, y);
    }
  }
}
int main() {
  cin >> N;
  vi P(N * N);
  for (int i = 0; i < (int)N * N; i++) {
    cin >> P[i];
    P[i]--;
  }
  dis = vvi(N, vi(N));
  check = vector<vector<bool>>(N, vector<bool>(N));
  for (int i = 0; i < (int)N; i++) {
    for (int j = 0; j < (int)N; j++)
      dis[i][j] = min(min(i + 1, N - i), min(j + 1, N - j));
  }
  int ans = 0;
  for (int i = 0; i < (int)N * N; i++) {
    ans += --dis[P[i] / N][P[i] % N];
    dfs(P[i] / N, P[i] % N);
  }
  for (int i = 0; i < (int)N; i++) {
    for (int j = 0; j < (int)N; j++) {
      cout << dis[i][j];
      if (j == N - 1) cout << endl;
    }
  }
  cout << ans << endl;
}
