Spiral Matrix

Free with account Updated Nov 19, 2026 · 6 min read
On this page

    Problem statement

    Given an m × n matrix, return all of its elements in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row, up the left column, and keep going inward ring by ring until every element has been visited once.

    A matrix-traversal question where the idea is easy and the difficulty is in the bounds: non-square matrices, a single row or column, and the last ring in the middle. Original problem: LeetCode 54.

    Example

    The outer ring gives 1 2 3 4 8 12 11 10 9 5; what's left inside is a single row, 6 7.
    The outer ring gives 1 2 3 4 8 12 11 10 9 5; what's left inside is a single row, 6 7.
    Input:  [[1,  2,  3,  4],
             [5,  6,  7,  8],
             [9, 10, 11, 12]]
    Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
    Input:  [[1], [2], [3]]        ->  [1, 2, 3]       # one column
    Input:  [[1, 2], [3, 4]]       ->  [1, 2, 4, 3]

    Constraints (assumed)

    • 1 ≤ m, n ≤ 10; the matrix is rectangular.

    What this question tests

    • Keeping four boundaries consistent while they move.
    • Handling the last ring, which may be a single row or a single column.
    • Writing loops whose ranges you can explain, not patch by trial and error.

    Questions to ask first

    1. Is the matrix always rectangular? (Here: yes.)
    2. Can it be empty? (Here: at least 1 × 1; returning an empty list for an empty matrix is cheap anyway.)
    3. Clockwise from the top-left? (Here: yes. Other directions are a common variant.)
    4. May I modify the matrix (for example, to mark visited cells)?