#t128. 填幻方
填幻方
Constructing a Magic Square
Problem Description
In an square grid, fill each cell with a distinct positive integer from to so that the sums of the numbers in every row, every column, and both main diagonals are equal; such a square is called a "magic square" (the sample shows a magic square). In ancient China it was called "Hetu", "Luoshu", or the "vertical-horizontal diagram".
A magic square looks magical, but when is odd there is a convenient construction:
- Initially the square is empty. First, put in the exact centre of the top row.
- From the last filled position, move up one cell; if already in the top row, wrap to the bottom row of the same column. Then move right one cell; if already in the rightmost column, wrap to the first column of the same row. If the new position is empty, fill it with the next number after the last filled one.
- If step 2 fails (the target cell is already filled), instead move down one cell from the last filled position; if already in the bottom row, wrap to the top row of the same column. This position is guaranteed to be empty. Fill it with the next number after the last filled one.
- Repeat steps 2 and 3 until all cells are filled, and the magic square is complete!
Write a program to construct an magic square following the rules above.
Input Format
The input is a positive odd integer , with guaranteed.
Output Format
Output lines, each containing space-separated positive integers: the magic square.
Sample Input
3
Sample Output
8 1 6
3 5 7
4 9 2
Sample Explanation
For , following the odd-order magic square construction:
- Put in the centre of the top row, i.e. row 1, column 2.
- From , move up and right: up goes to row 3 (wrapping past the top row to the bottom), right goes to column 3; position is empty, fill .
- From , move up and right: up to row 2, right to column 1 (wrapping past the rightmost column to the first); position is empty, fill .
- From , move up and right: up to row 1, right to column 2, but already holds , so step 2 fails. Instead move down from : down to row 3, column 1; position is empty, fill .
- Continue applying the rule to fill through , yielding the matrix above.
In this magic square, every row, every column, and both diagonals sum to .
Constraints
is a positive odd integer with .