Shift every element in a 2D grid to the right by positions, wrapping across rows as needed.
Shift 2D Grid
gfgProblem
You are given an grid of integers and a non-negative integer .
Perform a cyclic shift of the grid to the right by positions:
- Moving right from the last column of a row continues at the first column of the next row.
- Moving right from the last element of the grid continues at the first element of the grid.
Return the resulting grid after all shifts.
Intuition
This is a 2D indexing and simulation problem. One practical way to solve it is to treat the grid as a flattened array of length , shift indices by , and then map the result back into 2D form.
Input Format
- The first line contains two integers and .
- The next lines each contain integers describing the grid.
- The last line contains an integer .
Output Format
- Return the shifted grid as an matrix of integers.
Constraints
- Grid values fit in 32-bit signed integers
Example 1
Input
grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output
[[9,1,2],[3,4,5],[6,7,8]]
Explanation
A shift by 1 moves each element one step to the right in row-major order, with the last element wrapping to the front.
Example 2
Input
grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output
[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Explanation
A shift by 4 is equivalent to moving every row down by one row in flattened order.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.