Shift 2D Grid

Given an m x n grid and an integer k, shift the grid k times and return it. In one shift, grid[i][j] moves to grid[i][j + 1], grid[i][n - 1] moves to grid[i + 1][0], and grid[m - 1][n - 1] moves to grid[0][0].

30:00

Shift 2D Grid
easy
Free written solution
Topics
Companies

Given an m x n grid and an integer k, shift the grid k times and return it. In one shift, grid[i][j] moves to grid[i][j + 1], grid[i][n - 1] moves to grid[i + 1][0], and grid[m - 1][n - 1] moves to grid[0][0].

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]]
Constraints:
  • m=grid.lengthm = \text{grid.length}

  • n=grid[i].lengthn = \text{grid}[i]\text{.length}

  • 1≤m≤501 \leq m \leq 50

  • 1≤n≤501 \leq n \leq 50

  • −1000≤grid[i][j]≤1000-1000 \leq \text{grid}[i][j] \leq 1000

  • 0≤k≤1000 \leq k \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[1,2,3],[4,5,6],[7,8,9]],"k":1}

Shifting 1 time moves every value 1 step forward in reading order, wrapping from the last cell to the first.

k = 1

dest = (i·3 + j + k) % 9

the grid read as one ribbon

0

1

·

1

2

·

2

3

·

3

4

·

4

5

·

5

6

·

6

7

·

7

8

·

8

9

·

top: original order, bottom: after shifting 0

grid

1
2
3
4
5
6
7
8
9

result

Variables
VariableValue
m3
n3
k1
DepthFunction Call
Stack empty
0/13