← DiffPush

Spiral traversal

Standard Bar Arrays · Medium O(m * n) · O(1) auxiliary (excluding the output)

Reading a Wafer Map in a Spiral Sweep

An inspection head sweeps a rectangular wafer map starting at the top-left die and spirals inward clockwise, reporting each die it passes. The control software needs the same die sequence that the physical sweep would produce. The map is not necessarily square.

Input: An m x n matrix of integers.

Output: All elements of the matrix in clockwise spiral order, beginning with the top-left element.

Constraints

Examples

Example 1

Input: {"matrix":[[1,2,3],[4,5,6],[7,8,9]]}
Output: [1,2,3,6,9,8,7,4,5]
The sweep runs along the top, down the right, back along the bottom, up the left, and finishes at the centre.

Example 2

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]
With more columns than rows the inner ring degenerates into a single row, which is reported left to right.

Solve this in your browser →

Also on LeetCode ↗