美文网首页Leetcode
Leetcode 1914. Cyclically Rotati

Leetcode 1914. Cyclically Rotati

作者: SnailTyan | 来源:发表于2021-09-27 10:47 被阅读0次

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

1. Description

Cyclically Rotating a Grid

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

  1. https://leetcode.com/problems/cyclically-rotating-a-grid/

相关文章

网友评论

    本文标题:Leetcode 1914. Cyclically Rotati

    本文链接:https://www.haomeiwen.com/subject/ybggbltx.html