Ctrl K

Spiral Readout

Medium
You are given a rectangular table grid with m rows and n columns. Read all of its numbers in a spiral: start at the top-left corner, go right along the top row, then down the right edge, left along the bottom row, up the left edge, and keep going clockwise, winding towards the centre. Every cell is visited exactly once. Return the numbers in the order they are read.
Example 1
grid=[[5, 1, 8], [2, 9, 4]] → [5, 1, 8, 4, 9, 2]

The top row left to right gives 5, 1, 8; down the right edge gives 4; the bottom row right to left gives 9, 2.

Example 2
grid=[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]] → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

The numbers are placed so that the spiral walk visits them in order from 1 to 16.

Example 3
grid=[[-3], [0], [7]] → [-3, 0, 7]

With a single column the spiral simply goes top to bottom.

Constraints
  • 1 ≤ m, n ≤ 10
  • All rows have the same length n
  • -100 ≤ grid[i][j] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSpiral-Numbered Square MediumNext Step of a Cell Colony MediumZigzag Diagonal Sweep MediumMatch-Three Cascade MediumOutward Spiral Walk Medium
loading Python…
Input
grid=[[5, 1, 8], [2, 9, 4]]
Expected
[5, 1, 8, 4, 9, 2]

Run checks the first 3 tests in your browser. Submit checks all 52 tests on the server, hidden ones included.