All problems
0523MediumArrayMatrixSimulation

Spinning the Mosaic Layers

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1914Cyclically Rotating a Grid

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tile mosaic is stored as mosaic, a rectangular table of colour codes with an even number of rows and an even number of columns.

The mosaic is made of nested rings. The outermost ring is every cell on the border of the table; the next ring is the border of what is left once that ring is taken away, and so on. Because both side lengths are even, every ring is a closed loop of cells.

Read a ring by starting at its top-left cell and going clockwise: across its top row from left to right, down its right column, back across its bottom row from right to left, then up its left column. One shift moves the code in each position of that reading into the position one place earlier, and the code in the first position moves to the last position.

Every ring is shifted shifts times, all rings at once and each within itself. Return the mosaic afterwards.

Examples

Example 1

Input
mosaic = [[7, 9], [6, 8]], shifts = 1
Output
[[9, 8], [7, 6]]

The whole mosaic is one ring, read clockwise as 7, 9, 8, 6. After one shift each code sits one place earlier in that reading, so the reading becomes 9, 8, 6, 7.

Example 2

Input
mosaic = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], shifts = 2
Output
[[3, 4, 8, 12], [2, 11, 10, 16], [1, 7, 6, 15], [5, 9, 13, 14]]

The outer ring reads 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5 and the inner ring reads 6, 7, 11, 10. Each code moves two places earlier in its own reading.

Example 3

Input
mosaic = [[1, 2, 3, 4], [5, 6, 7, 8]], shifts = 7
Output
[[5, 1, 2, 3], [6, 7, 8, 4]]

This mosaic is a single ring, read clockwise as 1, 2, 3, 4, 8, 7, 6, 5. After seven shifts that same reading is 5, 1, 2, 3, 4, 8, 7, 6.

Constraints

  • rows == mosaic.length
  • cols == mosaic[i].length
  • 2 <= rows, cols <= 50
  • rows and cols are both even.
  • 1 <= mosaic[i][j] <= 5000
  • 1 <= shifts <= 10^9

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def spin_mosaic(mosaic: list[list[int]], shifts: int) -> list[list[int]]:
Java
public int[][] spinMosaic(int[][] mosaic, int shifts)
September 7
Apply