Cyclically Rotating a Grid Problem
Description
LeetCode Problem 1914.
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 k cyclic 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.lengthn == grid[i].length2 <= m, n <= 50- Both
mandnare even integers. 1 <= grid[i][j] <=50001 <= k <= 10^9
Solution
Approach: Rotate Each Layer
The grid splits into min(m, n) / 2 concentric rectangular layers, and each layer rotates independently.
For layer p, walk its border clockwise (top edge, right edge, bottom edge, left edge) and copy the values into an array nums of length l. Rotating the layer counterclockwise by k steps is the same as shifting this array by k mod l. So we walk the border again in the same order and write back nums[(k + t) mod l] for the t-th cell.
Taking k mod l first keeps k (up to 109) harmless.
Complexity: O(mn) time, since each cell is read and written once. O(m + n) extra space for the largest layer.
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
def rotate(p: int, k: int):
nums = []
for j in range(p, n - p - 1):
nums.append(grid[p][j])
for i in range(p, m - p - 1):
nums.append(grid[i][n - p - 1])
for j in range(n - p - 1, p, -1):
nums.append(grid[m - p - 1][j])
for i in range(m - p - 1, p, -1):
nums.append(grid[i][p])
k %= len(nums)
if k == 0:
return
nums = nums[k:] + nums[:k]
k = 0
for j in range(p, n - p - 1):
grid[p][j] = nums[k]
k += 1
for i in range(p, m - p - 1):
grid[i][n - p - 1] = nums[k]
k += 1
for j in range(n - p - 1, p, -1):
grid[m - p - 1][j] = nums[k]
k += 1
for i in range(m - p - 1, p, -1):
grid[i][p] = nums[k]
k += 1
m, n = len(grid), len(grid[0])
for p in range(min(m, n) >> 1):
rotate(p, k)
return grid