1. Description
2. Solution
**解析:**Version 1,先根据规律求出每一层的索引,然后按逆时针顺序保存到数组中,则k
次循环后当前索引的位置index
在列表中的位置为(index k) % len(circle)
,因此将当前索引位置的值赋给目标索引位置即可。
- Version 1
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
result = [[0] * n for _ in range(m)]
for i in range(min(m // 2, n // 2)):
circle = []
# Left column
circle = [(j, i) for j in range(i, m-i)]
# Bottom row
circle = [(m-1-i, j) for j in range(i 1, n-i)]
# Right column
circle = [(j, n-1-i) for j in range(m-2-i, i-1, -1)]
# Top row
circle = [(i, j) for j in range(n-2-i, i, -1)]
for index, (x, y) in enumerate(circle):
target_x, target_y = circle[(index k) % len(circle)]
result[target_x][target_y] = grid[x][y]
return result
Reference
- https://leetcode.com/problems/cyclically-rotating-a-grid/