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 togrid[i][j + 1]
. - Element at
grid[i][n - 1]
moves togrid[i + 1][0]
. - Element at
grid[m - 1][n - 1]
moves togrid[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