Maps app~20 min2s · 256 MBtarget O(n^2) time, O(n^2) spaceclassic twin: lc-48traversal
A map app draws a square picture from n by n tiles. Each cell holds the number of one tile image. The user turns the map clockwise by a quarter turn, and can repeat the gesture many times.
After a quarter turn the top left tile is in the top right corner. Each tile of the top row is now in the right column.
Write the picture after all the turns. The picture can have 300 rows and 300 tiles in a row, and the user can turn it up to 100,000 times.
Write rotate_tiles(tiles, turns).
tiles is a square grid with n rows and n places in each row. tiles[r][c] is the tile number at row r, place c.r, place c to row c, place n - 1 - r.turns quarter turns. turns can be 0.Input: tiles = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], turns = 1
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]Each tile at row r, place c moves to row c, place 2 - r.
| Tile | From (row, place) | To (row, place) |
|---|---|---|
| 1 | (0, 0) | (0, 2) |
| 2 | (0, 1) | (1, 2) |
| 3 | (0, 2) | (2, 2) |
| 4 | (1, 0) | (0, 1) |
| 5 | (1, 1) | (1, 1) |
| 6 | (1, 2) | (2, 1) |
| 7 | (2, 0) | (0, 0) |
| 8 | (2, 1) | (1, 0) |
| 9 | (2, 2) | (2, 0) |
Input: tiles = [[1, 2], [3, 4]], turns = 6
Output: [[4, 3], [2, 1]]Six quarter turns leave the same picture as two quarter turns, which is a half turn.
Input: tiles = [[9]], turns = 5
Output: [[9]]A picture of one tile never changes.
1 ≤ n ≤ 300 (rows, and places in each row)1 ≤ tiles[r][c] ≤ 1,000,000 (tile number)0 ≤ turns ≤ 100,000 (quarter turns clockwise)Turning the picture one quarter at a time costs 90,000 moves per turn. Over 100,000 turns that is 9,000,000,000 moves.
After four quarter turns every tile is back where it started. Only turns % 4 quarter turns can change the picture, so at most three are needed.