Matrix problems are mostly about keeping careful bounds. Walking a matrix in a spiral means: go right along the top row, down the right column, left along the bottom row, up the left column, then shrink all four boundaries and repeat.
A seed tray is a grid of cells, given as an m x n list of lists. A gardener checks every cell by walking a clockwise spiral: from the top-left corner along the top row, down the right-hand side, back along the bottom, up the left-hand side, and round again further in. Return a flat list of the cell values in the order she visits them.
Examples
Input: matrix = [[3, 8, 1],
[9, 4, 7],
[2, 6, 5]]
Output: [3, 8, 1, 7, 5, 6, 2, 9, 4]
Input: matrix = [[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33]]
Output: [10, 11, 12, 13, 23, 33, 32, 31, 30, 20, 21, 22]
Constraints
1 <= m, n <= 50- The matrix may be a single row, a single column, or non-square.
- Aim for O(m * n) time: every element is visited exactly once.
Goals
- Track four shrinking boundaries (top, bottom, left, right) while walking a matrix
- Traverse a row or column in the right direction with range()
- Guard against re-visiting a row or column when the remaining region is one row or column tall