本文主要是介绍Leetcode 1914. Cyclically Rotating a Grid,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
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 columncircle += [(j, i) for j in range(i, m-i)]# Bottom rowcircle += [(m-1-i, j) for j in range(i+1, n-i)]# Right columncircle += [(j, n-1-i) for j in range(m-2-i, i-1, -1)]# Top rowcircle += [(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/
这篇关于Leetcode 1914. Cyclically Rotating a Grid的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!