class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
while k:
cur = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n - 1):
cur[r][c + 1] = grid[r][c]
for r in range(m):
cur[(r + 1) % m][0] = grid[r][n - 1]
grid = cur
k -= 1
return gridWhere is the number of rows in the grid, is the number of columns in the grid, and is the shift count.
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
while k:
prev = grid[m - 1][n - 1]
for r in range(m):
for c in range(n):
grid[r][c], prev = prev, grid[r][c]
k -= 1
return gridWhere is the number of rows in the grid, is the number of columns in the grid, and is the shift count.
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
N = m * n
k %= N
arr = [0] * N
for r in range(m):
for c in range(n):
arr[r * n + c] = grid[r][c]
def reverse(l, r):
while l < r:
arr[l], arr[r] = arr[r], arr[l]
l += 1
r -= 1
reverse(0, N - 1)
reverse(0, k - 1)
reverse(k, N - 1)
for r in range(m):
for c in range(n):
grid[r][c] = arr[r * n + c]
return gridWhere is the number of rows in the grid and is the number of columns in the grid.
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
M, N = len(grid), len(grid[0])
def posToVal(r, c):
return r * N + c
def valToPos(v):
return [v // N, v % N]
res = [[0] * N for _ in range(M)]
for r in range(M):
for c in range(N):
newVal = (posToVal(r, c) + k) % (M * N)
newR, newC = valToPos(newVal)
res[newR][newC] = grid[r][c]
return resWhere is the number of rows in the grid and is the number of columns in the grid.