#C9168. Spiral Matrix Generation

    ID: 53231 Type: Default 1000ms 256MiB

Spiral Matrix Generation

Spiral Matrix Generation

You are given an integer \(n\) (with \(1 \le n \le 15\)). Your task is to generate an \(n \times n\) matrix filled with the integers from \(1\) to \(n^2\) in a spiral order (clockwise) and print the matrix with each element right-justified in a field of width 5.

If the input \(n\) is out of the allowed range, output an error message: "Invalid input. n must be between 1 and 15.". The program should repeatedly process inputs until a \(0\) is encountered, which terminates the input.

For example, when \(n = 3\), the spiral matrix is:

[ \begin{bmatrix} 1 & 2 & 3\ 8 & 9 & 4\ 7 & 6 & 5 \end{bmatrix} ]

and when \(n = 4\), the spiral matrix is:

[ \begin{bmatrix} 1 & 2 & 3 & 4\ 12 & 13 & 14 & 5\ 11 & 16 & 15 & 6\ 10 & 9 & 8 & 7 \end{bmatrix} ]

</p>

inputFormat

The input is read from stdin and consists of one or more integers separated by whitespace. Each integer \(n\) (except the terminating 0) requires you to generate and print the spiral matrix. The input is terminated by a 0, which should not be processed.

outputFormat

For each integer \(n\) (except 0), output the generated \(n \times n\) matrix to stdout. Each element in the matrix must be printed in a field of width 5 (right-justified) without additional spaces between them in the same row. After each matrix, print an empty line.

If \(n\) is not within the allowed range, output the exact error message:

Invalid input. n must be between 1 and 15.
## sample
3
0
    1    2    3
8    9    4
7    6    5

</p>