Skip to content
BytePatterns

Spiral Grid Walk

MediumArrays#matrix-traversal#boundary-shrinking~25m

Problem

Read every cell of a rectangular grid in a single inward spiral: across the top row, down the right column, back along the bottom row, up the left column, then repeat on whatever rectangle is left. Return the values in the order they are visited. The grid may have any width and height, including a single row or a single column.

Examples

Input:  [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Input:  [[1, 2],
         [3, 4],
         [5, 6]]
Output: [1, 2, 4, 6, 5, 3]
Why:    a tall grid spirals just the same
Input:  [[7]]
Output: [7]
Why:    edge case, a single cell is a complete spiral on its own

Hints

0 / 3

Stuck on the idea rather than the code? Spiral Order covers it.