DSA problem
Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order. Spiral order starts at the top-left corner and proceeds rightward, then downward, then leftward, then upward, peeling the matrix like the layers of an onion until every element has been collected.
The challenge is to traverse the matrix exactly once while correctly turning at the boundaries and never revisiting a cell. A clean way to manage this is to maintain four boundary pointers: top, bottom, left, and right. Each pointer marks the extent of the unvisited region, and after fully traversing a side, the corresponding boundary is moved inward to shrink the active rectangle.
The intuition for the optimal approach is layer-by-layer simulation. In each iteration, walk the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top, then contract the boundaries. Crucially, before traversing the bottom row or left column you must re-check that top <= bottom and left <= right to avoid double-counting elements in matrices that are not square. Each cell is visited once, yielding linear time.
Examples
matrix = [[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]matrix = [[7]][7]Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.