Problem
Given a positive integer $n$, generate a square matrix filled with elements from $1$ to $n^2$ in spiral order.
Example:
1 |
|
Explanation
- Similar to 54. Spiral Matrix, we create
top, right, bottom, left
variables. Then create acounter
starts from 1, fill the matrix. Whentop == bottom
orleft == right
, since it’s a square matrix, we check if inputn
is an odd number or not. If it’s event, then we are done. If it’s odd, there’s a middle element, and the middle element position will bematrix[n/2][n/2]
, so we fill it with thecounter
. Finally return the filled matrix.
Solution
1 |
|