medium +25 pts

Rotate Matrix Layers

Rotate each layer of a square matrix 90 degrees clockwise, layer by layer.

Write a function `rotate_layers(matrix)` that takes a square matrix (list of lists of integers) and rotates each concentric layer (ring) 90 degrees clockwise independently. The function should modify the matrix in-place and return the same matrix (do not create a new one). For a layer defined by its top-left corner (top, left) and bottom-right corner (bottom, right), rotating 90 degrees clockwise moves each element from top edge to right edge, right edge to bottom edge, bottom edge to left edge, left edge to top edge. For example, the outer layer of a 3x3 matrix rotates as: ``` 1 2 3 7 4 1 4 5 6 -> 8 5 2 7 8 9 9 6 3 ``` Note: For a 1x1 matrix, no change. The matrix entries can be any integers.

Constraints

- The matrix is square with size n where 0 <= n <= 100. - Each row has exactly n elements. - The matrix may be empty (n=0). - Must rotate each layer independently in-place.

Example

['>>> m = [[1,2,3],[4,5,6],[7,8,9]]\n>>> rotate_layers(m)\n[[7,4,1],[8,5,2],[9,6,3]]', '>>> m = [[1,2],[3,4]]\n>>> rotate_layers(m)\n[[3,1],[4,2]]', '>>> m = [[5]]\n>>> rotate_layers(m)\n[[5]]', '>>> m = []\n>>> rotate_layers(m)\n[]']
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider processing layers from outer to inner. For each layer, collect its elements in clockwise order, then rotate the collection by shifting positions.
For a layer, the number of elements is 4*(bottom-top). You can simulate rotation by moving values from one edge to the next.
Alternatively, you can rotate ring by ring using a temporary variable and performing swaps for each position on the top edge.
Think about the offset: for layer k, top=left=k, bottom=right=n-1-k. You only need to rotate n//2 layers.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.