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, leftvariables. Then create acounterstarts from 1, fill the matrix. Whentop == bottomorleft == right, since it’s a square matrix, we check if inputnis 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 | |