mediumMath / GeometryPure DSA~25 min
Read A Grid In Spiral Order
A heatmap renderer must serialise a 2D grid into a 1D stream following a spiral from the outer ring inward — top row, right column, bottom row, left column, repeating.
Problem
Given an m x n matrix, return all its elements in spiral order, starting at the top-left and moving clockwise inward.
Input
An m x n integer matrix.
Output
A list of all elements in spiral order.
Constraints
- 1 ≤ m, n ≤ 50
- -1000 ≤ matrix[i][j] ≤ 1000
Examples
Example 1
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,3,6,9,8,7,4,5]
Outer ring clockwise, then the center.
Example 2
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]
3x4 grid traversed spirally.