Deviopath › Python

Spiral Order of a Matrix

Hard · Algorithms

A matrix is a list of rows. Reading it in spiral order means: go right along the top row, down the right column, left along the bottom row, up the left column, then repeat on the smaller matrix inside.

A clean way is to keep four boundaries (top, bottom, left, right) and move them inward after each side.

Write spiral_order(matrix) that returns all values in spiral order as one list. The matrix is rectangular (every row has the same length) and may be empty ([]).

Next: Merge Overlapping Intervals