1 class Solution: 2 def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: 3 n = len(grid)#n行 4 m = len(grid[0])#m列 5 flat = [0] * (n * m) 6 t = 0 7 for i in range(n): 8 for j in range(m): 9 flat[t] = grid[i][j] 10 t += 1 11 k = k % (n * m) 12 tail = flat[:n*m-k] 13 head = flat[n*m-k:] 14 flat = head + tail 15 16 t = 0 17 newgrid = [[0 for _ in range(m)]for _ in range(n)] 18 for i in range(n): 19 for j in range(m): 20 newgrid[i][j] = flat[t] 21 t += 1 22 return newgrid
把二维数组 => 一维数组 => 一维数组变换 => 还原二维数组