Spiral Matrix
Spiral Matrix is LeetCode 54 (Medium). Given an m × n matrix, return all of its elements in clockwise spiral order: along the top row, down the right column, back along the bottom row, up the left column, then the same again on the ring inside.
The matrix need not be square, so single rows, single columns and thin leftover strips all occur.
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Intuition
Treat the cells you have not read yet as a rectangle fenced by four walls: top, bottom, left and right. One lap reads each wall in turn and pulls that wall inward by one, so the rectangle loses one ring per lap.
- What the walls guarantee: the cells between them are exactly the cells not yet output. When the walls cross, every cell has been read once.
- Why the walls are re-checked mid-lap: the top row and right column can use up the rectangle partway through a lap. The bottom and left walks must first confirm a row or column is still there, or they read cells a second time.
"Visit a grid ring by ring" is a boundary walk with shrinking walls. Spiral Matrix II, Rotate Image and printing a matrix in layers use the same four indices.
Approach
Before reading on, run your loop by hand on a single row such as [[1, 2, 3]]. Count how many times each value lands in the output. If any value appears twice, find which of the four walks ran when it should not have.
Two ways to solve it
Read one whole side at a time and move that side's wall inward.
- No extra grid: four integers track the unread rectangle.
- Watch out: the bottom and left walks need their own checks.
Step one cell at a time and turn clockwise whenever the next cell is outside the grid or already read.
- No guards: the loop runs exactly m × n times.
- Cost: a second grid remembers which cells were read.
Both run in O(m · n) time. The four walls win because they need no extra grid and the loop structure shows the spiral directly. The steps, code and live demo follow the walls, and the direction-turning code comes after the demo.
Put the walls on the edges
Set top = 0, bottom = m - 1, left = 0, right = n - 1. Loop while top <= bottom and left <= right, because that is exactly when unread cells remain.
Read the top row, then lower the top wall
Append matrix[top][left..right] from left to right, then add 1 to top. That row is finished, so moving the wall below it removes it from the rectangle.
Read the right column, then pull the right wall in
Append matrix[top..bottom][right] from top to bottom, then subtract 1 from right. Starting at the new top avoids reading the corner the top row already took.
Read the bottom row if a row is left
Only when top <= bottom, append matrix[bottom][right..left] from right to left and subtract 1 from bottom. Walking right to left keeps the spiral clockwise.
Read the left column if a column is left
Only when left <= right, append matrix[bottom..top][left] from bottom to top and add 1 to left. The next lap then starts on the ring one step inside.
Code in Python, C++ and Java
Step and turn with a seen grid
dr and dc hold the four moves in clockwise order: right, down, left, up. After reading a cell, look one step ahead. If that cell is off the grid or already in seen, add 1 to d (wrapping with % 4) and step that way instead. The loop runs exactly m * n times, so it never needs to test whether the walk is finished.
Common pitfalls
Checking the walls only at the top of the loop
for c in range(right, left - 1, -1):
out.append(matrix[bottom][c])
bottom -= 1if top <= bottom:
for c in range(right, left - 1, -1):
out.append(matrix[bottom][c])
bottom -= 1The while condition was true when the lap began, but the walls have moved since. On [[1, 2, 3]] the unguarded bottom walk reads the same row backwards and returns [1, 2, 3, 2, 1]. On [[1], [2], [3]] an unguarded left walk returns [1, 2, 3, 2].
Edge cases
The top walk reads the only cell and moves top past bottom. The right walk has an empty range, both guards fail, and the loop ends with one value.
The inner lap starts with top = bottom = 1 and left = right = 1. The top walk reads the centre cell, and every other walk is either empty or skipped by its guard.
Complexity
Spiral Matrix FAQ
How do you read the spiral counter-clockwise instead?
Change the order of the walks: down the left column, along the bottom row left to right, up the right column, then along the top row right to left. The checks move with them: the third and fourth walks are the ones that need left <= right and top <= bottom first.
How is Spiral Matrix II different?
Spiral Matrix II walks the same path but writes the numbers 1 to n² into an empty square grid instead of reading values out. Its grid is always square, which changes which checks it really needs.