Advanced · 2D lists · 178 of 264
Spiral order
Print the numbers of a matrix in spiral order: along the top row, down the right side, back along the bottom, up the left, and inwards.
Input: r and c, then r lines of c whole numbers. Output: the numbers in spiral order on one line.
Examples
Input
3 3 1 2 3 4 5 6 7 8 9
Output
1 2 3 6 9 8 7 4 5
Input
1 4 1 2 3 4
Output
1 2 3 4
Input
3 4 1 2 3 4 5 6 7 8 9 10 11 12
Output
1 2 3 4 8 12 11 10 9 5 6 7
One more test checks other inputs when you press Check.
Stuck? The idea behind 2d lists
A list of lists is a grid: grid[row][col]. Read one row per line, each turned into numbers.
Loop over rows, then over the columns inside each row. zip(*grid) turns rows into columns.
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
print(*row)
print(grid[1][2]) # 6Watch for: [[0] * 3] * 2 makes two names for the same row: changing one changes both. Build rows with a comprehension: [[0] * 3 for _ in range(2)].