from copy import deepcopyclassSolution:defshiftGrid(self,grid: List[List[int]],k:int) -> List[List[int]]: n =len(grid) m =len(grid[0])for _ inrange(k): old =deepcopy(grid)for i inrange(n):for j inrange(m):if j == m -1: grid[(i +1) % n][0] = old[i][j]elif i == n -1and j == m -1: grid[0][0] = old[i][j]else: grid[i][j +1] = old[i][j]return grid
## @lc app=leetcode.cn id=1260 lang=python3## [1260] 二维网格迁移## @lc code=startclassSolution:defshiftGrid(self,grid: List[List[int]],k:int) -> List[List[int]]: n =len(grid) m =len(grid[0])# 二维到一维 arr = [grid[i][j] for i inrange(n)for j inrange(m)]# 取模,缩小k的范围,避免无意义的运算 k %= m * n res = []# 首尾交换法defreverse(l,r):while l < r: t = arr[l] arr[l]= arr[r] arr[r]= t l +=1 r -=1# 三次旋转reverse(0, m * n - k -1)reverse(m * n - k, m * n -1)reverse(0, m * n -1)# 一维到二维 row = []for i inrange(m * n):if i >0and i % m ==0: res.append(row) row = [] row.append(arr[i]) res.append(row)return res# @lc code=end