LeetCode 1260. Shift 2D Grid 移动2D网格 (Easy)

Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
给定大小为m x n和整数k的2D网格。您需要将网格移动k次

In one shift operation:

  • Element at grid[i][j] moves to grid[i][j + 1].
  • Element at grid[i][n - 1] moves to grid[i + 1][0].
  • Element at grid[m - 1][n - 1] moves to grid[0][0].

Return the 2D grid after applying shift operation k times.

Example 1:

Example 1

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
</pre>

Example 2:

Example 2

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 50
  • 1 <= n <= 50
  • -1000 <= grid[i][j] <= 1000
  • 0 <= k <= 100

Solution:

class Solution:
    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
        num_rows, num_cols = len(grid), len(grid[0])
        # Create a new grid to copy into.
        for _ in range(k):
            new_grid = [[0] * num_cols for _ in range(num_rows)]
            # Case 1: Move everything not in the last column.
            for row in range(num_rows):
                for col in range(num_cols-1):
                    new_grid[row][col+1] = grid[row][col]
            # Case 2: Move everything in last column, but not last row.
            for row in range(num_rows-1):
                new_grid[row+1][0] = grid[row][num_cols-1]
            # Case 3: Move the bottom right.
            new_grid[0][0] = grid[num_rows-1][num_cols-1]
            grid = new_grid
   
        return grid

Element at grid[i][j] moves to grid[i][j + 1].
网格[i] [j]处的元素移至网格[i] [j +1]。

Diagram showing case #1.

Element at grid[i][n - 1] moves to grid[i + 1][0].
网格[i] [n-1]的元素移到网格[i +1] [0]。

Diagram showing case #2.

Element at grid[m - 1][n - 1] moves to grid[0][0].
网格[m-1] [n-1]的元素移至网格[0] [0]。

Diagram showing case #3.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容