2025-08-02 13:50:59 +0000 UTC
Shift 2D Grid
Categories:
Links
Code
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
if not grid or not grid[0]:
return grid
row_length = len(grid)
col_length = len(grid[0])
num_count = row_length * col_length
k %= num_count
res = [[0] * col_length for _ in range(row_length)]
for row in range(row_length):
for col in range(col_length):
flat_mat_index = (row * col_length) + col
new_flat_mat_index = (flat_mat_index + k) % num_count
new_row = new_flat_mat_index // col_length
new_col = new_flat_mat_index % col_length
res[new_row][new_col] = grid[row][col]
return res