Given a positive integer n, generate an n x nmatrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
Solutions
Solution 1: Simulation
We can directly simulate the process of generating the spiral matrix.
Define a 2D array \(\textit{ans}\) to store the spiral matrix. Use \(i\) and \(j\) to represent the current row and column indices, and use \(k\) to represent the current direction index. \(\textit{dirs}\) represents the mapping between direction indices and directions.
Starting from \(1\), fill each position in the matrix sequentially. After filling a position, calculate the row and column indices of the next position. If the next position is out of bounds or has already been filled, change the direction and then calculate the row and column indices of the next position.
The time complexity is \(O(n^2)\), where \(n\) is the side length of the matrix. Ignoring the space consumption of the answer array, the space complexity is \(O(1)\).