The “Spiral Matrix” problem is a classic 2D array traversal question. Given an m x n
matrix, your goal is to return all its elements in a spiral order—starting from the top-left corner and moving right, then down, then left, then up, and repeating this pattern inward until all elements are visited.
For example, if the input is:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]The output should be:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
.
This problem strengthens your understanding of matrix boundaries, direction handling, and loop control logic. It simulates real-world data processing patterns such as image filtering, robotic movement in 2D grids, or navigation algorithms in game development.
The spiral pattern can be visualized as a set of layers or “walls” that shrink as you complete each full cycle (right → down → left → up). Each layer peels off one ring of the matrix. To manage this, we maintain four boundaries:
UP_WALL
: the top boundary of unvisited rowsRIGHT_WALL
: the right boundary of unvisited columnsDOWN_WALL
: the bottom boundary of unvisited rowsLEFT_WALL
: the left boundary of unvisited columnsAs we traverse in a direction, we shrink the corresponding boundary to prevent re-visiting already-traversed cells.
m
) and columns (n
) in the matrix.ans
to store the spiral order result.RIGHT
, DOWN
, LEFT
, UP
.i
(row) and j
(column) to track the current position.UP_WALL = 0
DOWN_WALL = m
LEFT_WALL = -1
RIGHT_WALL = n
ans.length === m * n
:
j < RIGHT_WALL
. Append matrix[i][j]
to result and increment j
. After the loop, adjust pointers and decrement RIGHT_WALL
.i < DOWN_WALL
. Append matrix[i][j]
and increment i
. Then decrement DOWN_WALL
.j > LEFT_WALL
. Append matrix[i][j]
and decrement j
. Then increment LEFT_WALL
.i > UP_WALL
. Append matrix[i][j]
and decrement i
. Then increment UP_WALL
.Input:
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]Spiral steps:
Final result: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Time Complexity: O(m Ă— n), since we visit each element of the matrix exactly once.
Space Complexity: O(1) extra space (not counting the output array).
[]
The “Spiral Matrix” problem helps build intuition for controlled matrix traversal and multi-directional logic. By maintaining clear boundaries and moving in controlled directions, you can elegantly extract a spiral order from a 2D array. Mastering this problem improves your confidence in handling grid-based tasks, which are foundational in both interviews and real-world systems like image processing, simulations, and game development.