dsa · medium
Spiral Matrix II
Given a positive integer n, fill an n × n matrix with the numbers 1 through n² in clockwise spiral order, starting at the top-left and first moving right. Return that matrix.
Arguments
n— side length of the square matrix to fill
Example
n = 3 writes 1..9 as:
1 2 3 8 9 4 7 6 5
so [[1,2,3],[8,9,4],[7,6,5]].
n = 1 → [[1]].
n = 2 walks 1,2 then down to 3 then left to 4 → [[1,2],[4,3]].
Constraints
1 <= n <= 20 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.
Examples
Example 1
Input: 3 Expected: [[1,2,3],[8,9,4],[7,6,5]]
Example 2
Input: 1 Expected: [[1]]
Example 3
Input: 2 Expected: [[1,2],[4,3]]