Spiral Matrix
Core idea: A spiral is just four straight walks — right across the top, down the right, left across the bottom, up the left — repeated on a grid that keeps shrinking inward. Track four boundaries (
top,bottom,left,right); after each side, pull that boundary one step toward the centre. When the boundaries cross, the matrix is fully eaten. Novisitedarray, O(1) extra space.
1. The problem, in a fresh setting
You're writing a firmware routine for a thermal camera. The sensor hands you an m × n grid of temperature readings, and the display protocol wants the pixels streamed outside-in, clockwise — the outer ring first (so the operator sees the frame edge appear), then the next ring, spiralling toward the hot centre. You must flatten the 2D grid into that one spiral-ordered list.
Formally (LeetCode 54): given an m × n matrix, return all of its elements in spiral order — start at the top-left, go right across the top row, down the right column, left along the bottom row, up the left column, then step inward and repeat, until every cell is visited exactly once.
| Matrix | Spiral order |
|---|---|
[[1,2,3],[4,5,6],[7,8,9]] |
[1,2,3,6,9,8,7,4,5] |
[[1,2,3,4],[5,6,7,8],[9,10,11,12]] |
[1,2,3,4,8,12,11,10,9,5,6,7] |
[[7]] |
[7] |
Notice the middle row: it's 3 × 4 (non-square). The spiral doesn't care about squareness — it just keeps peeling whatever rectangle is left.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson