Leetcode 1914. Cyclically Rotating a Grid

2021-08-20 14:45:30 浏览数 (1)

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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/

0 人点赞