1260. Shift 2D Grid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
int m = grid.length, n = grid[0].length;

k = k % (m * n);

int[] tmp = new int[m * n];
int index = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[index++] = grid[i][j];
}
}

index = k == 0 ? 0 : -k + m * n;

List<List<Integer>> resultList = new ArrayList<>();
for (int i = 0; i < m; i++) {
List<Integer> numList = new ArrayList<>(n);
for (int j = 0; j < n; j++) {
numList.add(tmp[index]);
index = (index + 1) % (m * n);
}
resultList.add(numList);
}

return resultList;
}
}

References

1260. Shift 2D Grid