Spiral Matrix
The key idea
Maintain four shrinking boundaries —
top, bottom, left, right. Walk one edge at a time in the order right, down, left, up, and pull that boundary inward after each edge. The top <= bottom and left <= right guards stop you before the rings overlap, which also handles non-square shapes cleanly.Problem
Given an m x n matrix, return all elements of the matrix in spiral order.
Starting from the top-left corner, traverse the elements in a clockwise spiral: go across the top row, down the right side, back across the bottom row, up the left side, then continue inward ring by ring until every cell has been visited exactly once. Each value of matrix[i][j] appears in the output exactly once, and the returned list has length m * n.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Input: matrix = [[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]
Complexity
Time: O(m*n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Matrix / Grid problems
- Game of LifeMEDIUM
- Island PerimeterEASY
- Rotate ImageMEDIUM
- Search a 2D Matrix IIMEDIUM
- Set Matrix ZeroesMEDIUM
- Spiral Matrix IIMEDIUM
- Transpose MatrixEASY