codejump
MediumPro challengePythonJavaScriptTypeScript

Matrix — Spiral Order

AlgorithmsMatrixSimulation

solve(matrix) — matrix is a non-empty rows × cols grid (not necessarily square).
Return all its values in spiral order: left to right along the top row, down the right
column, right to left along the bottom row, up the left column, then spiral inward.

Keep four boundaries — top, bottom, left, right — and shrink one after each
side. The classic bug is on grids with a single remaining row or column: **re-check the
boundaries** before the way back, or you will visit cells twice.

Examples

solve([[1,2,3],[4,5,6],[7,8,9]])        → [1,2,3,6,9,8,7,4,5]
solve([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) → [1,2,3,4,8,12,11,10,9,5,6,7]
solve([[1],[2],[3]])                    → [1,2,3]

Sample tests

Test #13x3
Input: [[[1,2,3],[4,5,6],[7,8,9]]]
Output: [1,2,3,6,9,8,7,4,5]
Test #2Wide 3x4
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]
Test #3Single cell
Input: [[[1]]]
Output: [1]