Spiral Matrix II
Spiral Matrix II is LeetCode 59 (Medium). Given a positive integer n, build an n × n grid that holds the numbers 1 to n², placed in clockwise spiral order starting from the top-left corner.
With n at most 20 the grid has at most 400 cells, so writing each cell directly is all the work there is.
- 1 <= n <= 20
Intuition
Fill the grid the way you would paint a square frame, from the outside in. Four walls, top, bottom, left and right, mark the square still blank. One lap paints its top row, right column, bottom row and left column, and each wall steps inward after its side is done. A single counter hands out 1, 2, 3 and so on, so the only real job is to visit every cell exactly once, in spiral order.
Because the grid is square, the walls close in evenly from all four sides. The loop is never left with a long thin strip, which is what forces extra checks in the reading version of this walk.
"Write numbers into a grid along a path" is the reading walk of Spiral Matrix run in reverse: the same four walls, with each visit storing a value instead of collecting one.
Approach
Before reading on, fill a 4 × 4 grid by hand with four walls and write down the wall values at the start of the second lap. Then check what each of the four loops does on that 2 × 2 lap, and whether any of them needs an if in front of it.
Two ways to solve it
Write one side at a time and move that wall inward.
- Square grid: no checks inside the lap.
- Easy to trace: each loop is one side of the ring.
Write one number per step and turn clockwise when the next cell is off the grid or already holds a number.
- Free marker: a 0 means "not written yet", so no extra grid is needed.
- Fixed length: the loop runs exactly n² times.
Both run in O(n²) time and need nothing beyond the output grid. The four walls win because each side is one plain loop and the lap structure is easy to check by hand. The steps, code and live demo follow the walls, and the turn-when-blocked code comes after the demo.
Make the grid and put the walls on its edges
Create an n × n grid of zeros, set top = left = 0 and bottom = right = n - 1, and start val at 1. Loop while top <= bottom; in a square, left and right meet on the same lap, so this one test covers both.
Write the top row, then the right column
Walk the top row left to right, writing val and adding 1 each time, then move top down. Walk the right column from the new top down to bottom, then move right in. Starting at the new top keeps the corner from being written twice.
Write the bottom row, then the left column
Walk the bottom row from right back to left, move bottom up, then walk the left column from bottom up to top and move left in. No if is needed: on a final single-cell lap all three of the right, bottom and left loops have empty ranges, and on a final 2 × 2 lap only the left loop does.
Code in Python, C++ and Java
Write and turn when blocked
The grid starts full of zeros, and every written cell holds a number from 1 up, so a non-zero cell is a wall the walk has built itself. dr and dc list the moves right, down, left, up; after each write, look one step ahead and turn clockwise if that cell is off the grid or already filled.
Common pitfalls
Building the rows with list multiplication
grid = [[0] * n] * n
grid = [[0] * n for _ in range(n)]
Multiplying the outer list copies one row object n times, so writing to any row writes to all of them. For n = 2 the result is [[4, 3], [4, 3]] instead of [[1, 2], [4, 3]].
Turning only at the edge of the grid
if not (0 <= nr < n and 0 <= nc < n):
d = (d + 1) % 4if not (0 <= nr < n and 0 <= nc < n) or grid[nr][nc]:
d = (d + 1) % 4In the turn-when-blocked version, a filled cell must also force a turn. With only the edge test, n = 3 walks round the outer ring a second time: 9 lands on top of 1 and the centre stays 0, giving [[9, 2, 3], [8, 0, 4], [7, 6, 5]].
Edge cases
The top-row loop writes 1 into the only cell. The other three loops have empty ranges, the walls cross, and the answer is [[1]].
Complexity
Spiral Matrix II FAQ
Is there a formula for the number in row i, column j?
Yes. The cell sits on ring k = min(i, j, n - 1 - i, n - 1 - j), and the rings outside it hold 4k(n - k) numbers. Add the cell's position along its own ring, counted clockwise from that ring's top-left corner, plus 1. This answers one cell in O(1) without building the grid.
How do you make the spiral start from the centre instead?
Fill the grid as usual, then replace every value v with n² + 1 - v. The largest number ends up in the top-left corner and 1 lands on the last cell of the clockwise walk, so reading upwards from 1 traces the spiral outward, counter-clockwise.