P2615 [NOIP 2015 Senior] The Magical Magic Square

Background

NOIP 2015 Senior Day 1 T1.

Description

A magic square is a very special $N \times N$ matrix: it consists of the numbers $1,2,3,\cdots,N \times N$, and the sums of every row, every column, and the two diagonals are all the same. When $N$ is odd, we can construct a magic square by the following method: First, write $1$ in the middle of the first row. Then fill each number $K$ in increasing order ($K=2,3,\cdots,N \times N$) as follows: 1. If $(K-1)$ is in the first row but not in the last column, then place $K$ in the last row, in the column immediately to the right of the column of $(K-1)$. 2. If $(K-1)$ is in the last column but not in the first row, then place $K$ in the first column, in the row immediately above the row of $(K-1)$. 3. If $(K-1)$ is in the first row and the last column, then place $K$ directly below $(K-1)$. 4. If $(K-1)$ is neither in the first row nor in the last column, then if the cell to the upper-right of $(K-1)$ is still empty, place $K$ there; otherwise, place $K$ directly below $(K-1)$. Given $N$, construct the $N \times N$ magic square using the method above.

Input Format

A positive integer $N$, the size of the magic square.

Output Format

Output $N$ lines, each containing $N$ integers. Adjacent integers are separated by a single space. The output is the $N \times N$ magic square constructed by the method above.

Explanation/Hint

Constraints: For $100\%$ of the testdata, $1 \leq N \leq 39$ and $N$ is odd. Translated by ChatGPT 5