227. Spiral Reader
A museum floor is a rectangle of rooms laid out in a grid with m rows and n columns, and grid[i][j] is the number of visitors in the room at row i, column j. A guard starts in the top-left room and walks a clockwise spiral: first along the top row to the right, then down the last column, then left along the bottom row, then up the first column, and then repeats the same pattern on the inner rectangle that is left, until every room has been visited exactly once.
Return the visitor counts in the order the guard visits the rooms. The grid can have a million rooms, so the walk must be efficient: do not copy or reshape the grid on every step.
Example 1
- Input:
- grid = [[4,8,15],[16,23,42]]
- Output:
- [4,8,15,42,23,16]
- Explanation:
Right along the top row: 4, 8, 15. Down the last column: 42. Left along the bottom row: 23, 16. The first column's remaining room was already visited. Result 4, 8, 15, 42, 23, 16.
Example 2
- Input:
- grid = [[7]]
- Output:
- [7]
- Explanation:
A single room is visited immediately.
Example 3
- Input:
- grid = [[1,2],[3,4],[5,6]]
- Output:
- [1,2,4,6,5,3]
- Explanation:
Top row 1, 2; down the right column 4, 6; left along the bottom row 5; up the left column 3. Result 1, 2, 4, 6, 5, 3.
Constraints
1 ≤ m, n ≤ 1000 (up to 106 rooms)
-109 ≤ grid[i][j] ≤ 109
All rows have the same length.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 ms
Expected complexity
- Time
- O(m × n)
- Space
- O(1) extra besides the output