Cyclically Rotating a Grid — LeetCode 1914 Python Solution
- Problem
- #1914
- Pattern
- Matrix and Grid
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- grid = [[40,10],[30,20]], k = 1
- Output
- [[10,20],[40,30]]
- Explanation
- The figures above represent the grid at every state.
Python solution
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 gridComplexity
| Measure | Complexity |
|---|---|
| Time | O(m·n) |
| Space | O(1) to O(m·n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1914. Cyclically Rotating a Grid is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1914. Cyclically Rotating a Grid?
- LeetCode 1914. Cyclically Rotating a Grid is rated Medium on LeetCode.
- What topics does LeetCode 1914. Cyclically Rotating a Grid cover?
- LeetCode 1914. Cyclically Rotating a Grid is tagged Array, Matrix and Simulation on LeetCode.