// yukicoder: No.217 魔方陣を作ろう // 2019.5.11 #include #include #if 1 #define gc() getchar_unlocked() #define pc(c) putchar_unlocked(c) #else #define gc() getchar() #define pc(c) putchar(c) #endif int in() // 非負整数の入力 { int n = 0, c = gc(); do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0'); return n; } int maxv = 2; void out(int n) // 非負整数の表示(出力) { int i, j; char b[20]; i = 0; while (n) b[i++] = n % 10 + '0', n /= 10; j = maxv-i; while (j--) pc(' '); while (i--) pc(b[i]); } int tbl[22][22]; int buf[22][22]; void odd_magic(int n) { int i, r, c; i = 0; for (r = -(n>>1); r <= (n>>1); r++) for (c = 0; c < n; c++) tbl[(r+c+n) % n][(c-r+n) % n] = ++i; } void quad_magic(int n) { int i, r, c; int k[4][2] = {{0,3},{1,2},{1,2},{0,3}}; i = 1; for (r = 0; r < n; r++) for (c = 0; c < n; c++) { if ((c&3) == k[r&3][0] || (c&3) == k[r&3][1]) tbl[r][c] = i; else tbl[r][c] = n*n-i+1; i++; } } void swap(int i, int j, int k, int l) { int t = buf[i][j]; buf[i][j] = buf[k][l]; buf[k][l] = t; } void even_magic(int n) { int r, c; int m = n >> 1, m2 = m*m, k = (m-1) >> 1; odd_magic(m); for (r = 0; r < m; r++) for (c = 0; c < m; c++) { buf[r][c] = buf[r+m][c] = buf[r][c+m] = buf[r+m][c+m] = tbl[r][c]; buf[r+m][c+m] += m2; buf[r][c+m] += m2 << 1; buf[r+m][c] += m2 * 3; } if (k > 1) for (r = 0; r < m; r++) for (c = 1; c < k; c++) swap(r, c, r+m, c), swap(r, n-k+c, r+m, n-k+c); for (r = 0; r < k; r++) swap(r, 0, r+m, 0), swap(r+k+1, 0, r+k+1+m, 0); swap(k, k, k+m, k); memcpy(tbl, buf, sizeof(buf)); } int main() { int N, r, c; N = in(); if ((N & 3) == 0) quad_magic(N); else if (N & 1) odd_magic(N); else even_magic(N); if (N == 3) maxv = 1; else if (N >= 10) maxv = 3; for (r = 0; r < N; r++) { out(tbl[r][0]); for (c = 1; c < N; c++) pc(' '), out(tbl[r][c]); pc('\n'); } return 0; }