Skip to content

Commit 4597e34

Browse files
authored
Merge pull request #1738 from AP-Repositories/patch-21
Create 1260-shift-2d-grid.java
2 parents 77ec919 + 50c2937 commit 4597e34

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Diff for: java/1260-shift-2d-grid.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
static final int ROW = 0, COL = 1;
3+
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
4+
final int M = grid.length, N = grid[0].length;
5+
6+
BiFunction<Integer, Integer, Integer> posToVal = (r, c) ->
7+
r * N + c;
8+
Function<Integer, int[]> valToPos = (v) ->
9+
new int[] {v / N, v % N};
10+
11+
List<List<Integer>> res = new ArrayList<>();
12+
for(int i = 0; i < M; i++) {
13+
Integer[] tmp = new Integer[N];
14+
for(int j = 0; j < N; j++)
15+
tmp[j] = 0;
16+
res.add(Arrays.asList(tmp));
17+
}
18+
for(int r = 0; r < M; r++)
19+
for(int c = 0; c < N; c++) {
20+
int newVal = (posToVal.apply(r, c) + k) % (M * N);
21+
int[] newRC = valToPos.apply(newVal);
22+
res.get(newRC[ROW]).set(newRC[COL], grid[r][c]);
23+
}
24+
return res;
25+
}
26+
}

0 commit comments

Comments
 (0)