Leetcode 1914. Cyclically Rotating a Grid

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Cyclically Rotating a Grid

2. Solution

解析:Version 1,先根据规律求出每一层的索引,然后按逆时针顺序保存到数组中,则k次循环后当前索引的位置index在列表中的位置为(index+k) % len(circle),因此将当前索引位置的值赋给目标索引位置即可。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

  1. https://leetcode.com/problems/cyclically-rotating-a-grid/
如果有收获,可以请我喝杯咖啡!