#P2615. Constructing an Odd Magic Square
Constructing an Odd Magic Square
Constructing an Odd Magic Square
A magic square is an amazing \(N \times N\) matrix that is filled with the numbers \(1, 2, 3, \dots, N \times N\) such that the sum of the numbers in each row, each column, and both main diagonals are the same.
When \(N\) is odd, a magic square can be constructed using the following procedure:
- Place \(1\) in the middle column of the first row.
- For each \(K\) from \(2\) to \(N \times N\), let the position of \(K-1\) be \((i, j)\) (0-indexed). Then:
- If \(K-1\) is in the first row but not in the last column (i.e. \(i = 0\) and \(j \neq N-1\)), place \(K\) in the last row and the column \(j+1\) (i.e. \((N-1, j+1)\)).
- If \(K-1\) is in the last column but not in the first row (i.e. \(j = N-1\) and \(i \neq 0\)), place \(K\) in the first column and the row \(i-1\) (i.e. \((i-1, 0)\)).
- If \(K-1\) is at the first row and last column (i.e. \((0, N-1)\)), place \(K\) directly below \(K-1\) (i.e. \((i+1, j)\)).
- Otherwise (i.e. when \(K-1\) is neither in the first row nor in the last column), check the cell \((i-1, j+1)\):
- If it is empty, place \(K\) at that cell.
- If it is already filled, place \(K\) directly below \(K-1\) (i.e. \((i+1, j)\)).
Given an odd integer \(N\), construct the corresponding \(N \times N\) magic square using the above algorithm.
inputFormat
The input consists of a single odd integer \(N\) (\(1 \leq N \leq 99\)).
outputFormat
Output the constructed magic square. Print each row on a new line, and separate the numbers in a row with a single space.
sample
3
8 1 6
3 5 7
4 9 2
</p>