You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
Return the matrix after applying kcyclic rotations to it.
Example 1:
Input: grid = [[40,10],[30,20]], k = 1
Output: [[10,20],[40,30]]
Explanation: The figures above represent the grid at every state.
Example 2:
Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
Explanation: The figures above represent the grid at every state.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 50
Both m and n are even integers.
1 <= grid[i][j] <=5000
1 <= k <= 109
Solutions
Solution 1: Layer-by-Layer Simulation
Thinking
Layers are disjoint cycles and \(k\) may exceed a cycle length, so stepping cell by cell wastes work. Flatten each layer clockwise, reduce \(k\) modulo its length, then write back.
Collect top, right, bottom, and left in that order and restore in the same order. Layers are independent, so the total time is linear in the grid size.
First, we compute the number of layers in the matrix, denoted by \(p\), and then simulate the cyclic rotation layer by layer from the outside to the inside.
For each layer, we traverse clockwise and append the elements on the top, right, bottom, and left edges to an array \(nums\) in order. Let the length of \(nums\) be \(l\). Next, we take \(k \bmod l\). Then, starting from index \(k\) in the array, we write the elements back to the matrix along the top, right, bottom, and left edges in order.
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m + n)\), where \(m\) and \(n\) are the number of rows and columns of the matrix, respectively.