222. Spiral Painter
A robot paints numbers on a square floor made of side × side tiles. It starts on the top-left tile facing right and writes 1. Then it keeps walking one tile at a time and writes the next number 2, 3, 4, ... on each new tile. Whenever the next tile in its current direction is outside the floor or has already been painted, the robot turns clockwise (right, then down, then left, then up, then right again) and carries on. It stops after writing side × side.
Return the finished floor as a grid of side rows and side columns, where grid[i][j] is the number written on the tile in row i, column j. The floor can be up to 1000 tiles wide, so painting must be quick.
Example 1
- Input:
- side = 4
- Output:
- [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
- Explanation:
The robot paints the top row 1 to 4, turns down the right column 5 to 7, goes left along the bottom row 8 to 10, goes up the left column 11, 12, then spirals into the middle 13 to 16.
Example 2
- Input:
- side = 2
- Output:
- [[1,2],[4,3]]
- Explanation:
1 and 2 along the top row, then 3 on the bottom right and 4 on the bottom left.
Example 3
- Input:
- side = 1
- Output:
- [[1]]
- Explanation:
One tile, one number.
Constraints
1 ≤ side ≤ 1000
The result contains the numbers 1 to side × side, each exactly once.
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(side<sup>2</sup>)
- Space
- O(side<sup>2</sup>) for the output