zoukankan      html  css  js  c++  java
  • 1260. Shift 2D Grid

    Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

    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.

    每次shift,就是每个元素往右移动,移动到边界了就往下一行走,如果行到底了就回到第一行。

    可以把位置看成i*m+j,那么移动k补之后的位置就是(i * m + j + k) % (m * n), 除以m得到行new_i, 位置 - new_i * m 得到新列new_j

    class Solution(object):
        def shiftGrid(self, grid, k):
            """
            :type grid: List[List[int]]
            :type k: int
            :rtype: List[List[int]]
            """
            matrix = []
            n = len(grid)
            m = len(grid[0])
            for i in range(n):
                matrix.append([0] * m)
            
            for i in range(n):
                for j in range(m):
                    x = (i * m + j + k) % (m * n)
                    new_i = x // m
                    new_j = x - new_i * m
                    print(i, j, x, new_i, new_j)
                    matrix[new_i][new_j] = grid[i][j]
            return matrix
  • 相关阅读:
    Unbuntu--安装VMware Tools
    方法引用的基本使用
    Stream流
    Stream流的常用方法
    枚举
    编程式路由导航
    向路由组件传递数据
    缓存路由组件
    嵌套路由
    基本路由
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13226727.html
Copyright © 2011-2022 走看看