Spiral order
Inputs
cells is a grid: a list of 1 to 5 rows, each with the same number (1 to 5) of whole numbers from 0 to 99.
Your tasks
- Keep four edges:
top,bottom,leftandright, starting at the outside of the grid. - Use a
whileloop that runs whiletop <= bottomandleft <= right. Each round, walk the top row left to right, the right column downward, the bottom row right to left and the left column upward, adding each cell toorder. Move each edge inward after you walk along it. - Check that
top <= bottomandleft <= rightstill hold before walking the bottom row and left column, so a single row or column is not walked twice. - Complete
spiralso it returnsorder. Return it, do not print it.
Example
With cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], spiral returns [1, 2, 3, 6, 9, 8, 7, 4, 5].
Rules
- Start at the top-left cell and go clockwise.
Test data
TEST DATA 1: cells is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
TEST DATA 2: cells is [[5]]
Practice focus
Two-dimensional data is a loop over rows with a loop over columns inside. Grids lead straight to flood fill, islands, dynamic programming tables and path problems.