1162. Spiral From the Centre
A museum floor is an n x n grid of tiles with n odd, and grid[i][j] is the number shown on a tile. A guide starts on the centre tile and tours the floor in an expanding square spiral: one tile right, one down, two left, two up, three right, three down, and so on, where the run length grows by one after every second turn.
Return the numbers in the exact order the guide visits them, starting with the centre tile, and stop as soon as all n * n tiles have been visited once. The rule fixes the order completely, so there is no tie to break; the walk never leaves the floor before every tile is covered. Here 1 <= n <= 49 and each value lies in [-10^4, 10^4].
A direct simulation with four direction vectors runs in O(n^2) time and needs only O(1) extra space besides the answer.
Example 1
- Input:
- grid = [[5]]
- Output:
- [5]
- Explanation:
A 1 x 1 floor has only the centre tile, so the tour is just that value.
Example 2
- Input:
- grid = [[1,2,3],[4,5,6],[7,8,9]]
- Output:
- [5,6,9,8,7,4,1,2,3]
- Explanation:
The guide starts on 5, then walks right to 6, down to 9, left through 8 and 7, up through 4 and 1, and right through 2 and 3.
Example 3
- Input:
- grid = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]
- Output:
- [13,14,19,18,17,12,7,8,9,10,15,20,25,24,23,22,21,16,11,6,1,2,3,4,5]
- Explanation:
From centre 13 the walk goes 14, 19, 18, 17, 12, 7, 8, 9, 10, 15, 20, 25, then sweeps back along the bottom row, up the left column and across the top row to finish at 5.
Constraints
1 ≤ n ≤ 49, n is odd
-104 ≤ grid[i][j] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n^2)
- Space
- O(n^2)