59/670

59. Spiral Matrix II

Medium

Write a function that receives a single integer n and returns an n × n grid filled with the numbers 1 through , placed along a clockwise spiral: begin in the top-left cell, sweep right across the top row, then down the right column, then left across the bottom row, then up the left column, and keep coiling inward until every cell is filled.

For n = 3 the grid comes out as:

1 2 3
8 9 4
7 6 5

Return the grid as a list of n rows, each a list of n integers.

Clockwise spiral fill for n = 3
123894765start top-left,sweep clockwise,coil inward untiln² cells are filled

Example 1:

Input: n = 3

Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

Explanation: 1→2→3 fills the top row, 4→5 walks down the right side, 6→7 sweeps left along the bottom, 8 climbs back up, and 9 lands in the center.

Example 2:

Input: n = 1

Output: [[1]]

Explanation: A 1 × 1 grid holds just the number 1.

Constraints:

  • 1 ≤ n ≤ 20

Hints:

Think of the grid as concentric rings. Fill the outermost ring completely (top row → right column → bottom row → left column), then recurse on the (n-2) × (n-2) grid inside.

Keep four boundaries — top, bottom, left, right — and shrink the matching one after finishing each side. Guard the bottom row and left column passes so a single leftover row or column isn't written twice.

Alternative: simulate a walker with a direction vector (dr, dc) that turns right whenever the next cell is off-grid or already filled.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: n = 3

Expected output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]