67. Spiral order
A grid is a list of rows, each a list of the same length. Write a function spiral(grid) that returns all of the
grid's items in spiral order: start at the top-left corner, go right along the top row, down the right column, left
along the bottom row, up the left column, and keep circling inward until every item has been read once.
- Every item appears exactly once in the result.
- A grid with a single row or a single column is read straight through.
- An empty grid
[]gives[].
Example 1
grid = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]][1, 2, 3, 6, 9, 8, 7, 4, 5]Example 2
grid = [[1, 2, 3, 4],
[5, 6, 7, 8]][1, 2, 3, 4, 8, 7, 6, 5]Example 3
grid = [[1], [2], [3]][1, 2, 3]Constraints
gridhas 0 to 10 rows; every row has the same number of items, 1 to 10.- The items are whole numbers.
Submit also runs 8 more tests you can't see.
Practises Lists (lesson 9).
- Keep four edges of the part not read yet:
top,bottom,leftandright, row and column numbers that start at the grid's borders. - Read the top row from
lefttoright, then movetopdown by one. Do the same for the right column (then moverightin), the bottom row backwards and the left column upwards. - Before reading the bottom row, check
top <= bottomagain, and before the left columnleft <= right: with one row or column left, they were already read.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def spiral(grid):
"""Read a grid's items in clockwise spiral order.
grid: list of rows, each a list of the same length;
may be empty
Returns: list, every item once, in spiral order
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.