Music streaming app~20 min2s · 256 MBtarget O(m * n) time, O(1) spaceclassic twin: lc-54traversal
A cinema hall is a grid of seats. Each cell holds the number printed on one seat ticket. The ushers call the numbers in a spiral. They go along the front row to the right, down the right side, back along the last row, and up the left side.
When the outer ring is done, the ushers continue on the ring inside it, and so on until every seat has been called once.
The hall has up to 600 rows and 600 seats in a row. A hall can also be a single row or a single column.
Write spiral_order(seats).
seats[r][c] is the ticket number of the seat in row r and place c. All rows have the same length.Input: seats = [[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]The hall has 3 rows and 4 places. Each ring reads four sides in turn, and a side is empty when the ring is too thin.
| Ring | Top row | Right column | Bottom row | Left column |
|---|---|---|---|---|
| 0 | 1, 2, 3, 4 | 8, 12 | 11, 10, 9 | 5 |
| 1 | 6, 7 | none | none | none |
Input: seats = [[7, 8, 9]]
Output: [7, 8, 9]A single row is read from left to right and nothing is read twice.
Input: seats = [[1], [2], [3], [4]]
Output: [1, 2, 3, 4]A single column is read from top to bottom.
1 ≤ seats.length ≤ 600 (rows)1 ≤ seats[r].length ≤ 600 (places in a row, the same for every row)1 ≤ seats[r][c] ≤ 1,000,000 (ticket number)There are 360,000 seats. Taking the top row and then rebuilding the rest of the grid after a quarter turn rebuilds about 108,180,000 cells in all.
Four moving edges visit each seat exactly once, so 360,000 steps are enough.