← DSA Atlas
Dedicated problem page · #59

Spiral Matrix II

MediumMatrix and SimulationShrinking boundary fillBoundary pointers (simulation)
Solve on LeetCode ↗
59
MediumMatrix and SimulationBoundary pointers (simulation)Shrinking boundary fill

Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with the elements from 1 to n^2 placed in clockwise spiral order starting at the top-left corner.

Open official problem prompt ↗
In plain English

Produce the n x n grid whose cells hold 1..n^2 laid down along a clockwise inward spiral.

Picture it like this

Like coiling a rope neatly into a square bin, laying each successive foot of rope next to the last as you wind inward.

Example
Input
n = 3
Output
[[1,2,3],[8,9,4],[7,6,5]]
Why
Writing 1..9 clockwise from the top-left fills the outer ring 1..8 and leaves 9 in the center.
Constraints
1 <= n <= 20
Pattern lesson

See the pattern, then code

Shrinking boundary fill
Recognition clue

'Fill a matrix in spiral order' is the write-mode twin of Spiral Matrix: instead of reading cells you assign an incrementing counter along the same four shrinking boundaries.

Matrix and Simulation

Rotations, boundary walks, direction changes, or careful in-place state updates.. Maintain a running number starting at 1 and the same four walls as spiral traversal. Whenever you would read a cell, instead write the next number and increment it.

New words, made simpleKnow these before the algorithm
Boundary pointer
Index of the current top/bottom/left/right wall of the unfilled region.
Running counter
The variable num that supplies the next value to write.
Ring
One clockwise loop of the four boundary passes.
Approaches from first idea to best ideaCompare the trade-offs
ApproachHow it thinksCost
Direction turning with bounds check

Valid, but the turn logic and filled-cell checks are fiddlier.

Move in the current direction, turn right when the next cell is filled or off-grid.

Time O(n^2)Space O(1)
The rule we keep true

Invariant

num equals one more than the count of cells already filled, and top/bottom/left/right bound the still-empty rectangle.

Why this is correct

Reasoning

Each pass fills a full current edge with consecutive numbers and then retracts that edge, so exactly n^2 assignments happen, each cell once, in strictly increasing spiral order. The inner guards stop a collapsed rectangle from being written twice.

The algorithm in three movesSay these aloud before coding
1Allocate an n x n matrix of zeros and set top, bottom, left, right and num = 1

top row: (0,0)=1,(0,1)=2,(0,2)=3

2Fill the top row left-to-right, then move top down

right col: (1,2)=4,(2,2)=5

3Fill the right column top-to-bottom, then move right in

bottom row: (2,1)=6,(2,0)=7

4Fill the bottom row right-to-left and the left column bottom-to-top, moving those walls in

left col: (1,0)=8; center (1,1)=9

5Repeat until the walls cross, then return the matrix

Visual trace

Follow the data, one decision at a time

Input snapshotHighlighted cells are involved in this example
10
21
32
43
54
65
76
87
98
1 · Readnum=1..3
2 · AskFill row 0?
3 · Update statetop=0
4 · Result(0,0..2)=1,2,3; top=1, num=4
Key takeaway

Numbers 1..9 as they are written clockwise into the 3x3 grid.

Code walkthrough

Read the solution in small chunks

Python 3

Do not memorize the whole program. Connect each group of lines to one job in the algorithm.

  1. 1
    Lines 3-5Allocate and initialize

    Zero grid, four walls at the edges, counter at 1.

  2. 2
    Lines 7-14Top and right fills

    Always valid on entry per the while guard; shrink top then right after writing.

  3. 3
    Lines 15-24Guarded bottom and left fills

    The two if checks prevent overwriting when the rectangle has narrowed to a single row or column.

Make it stick

Edge cases, mistakes, and one self-check

E

Edge cases to test

  • n == 1 returns [[1]]
  • Even n where there is no single center cell
  • Largest n = 20 (fills 400 cells)
!

Common beginner mistakes

  • Dropping the top<=bottom / left<=right guards, which overwrites cells and skips numbers for odd n
  • Initializing num to 0 instead of 1
  • Reusing spiral-read code but forgetting to increment num on every write
Check your understanding

For even n, why is no explicit center handling needed?