MCPcopy Index your code
hub / github.com/neetcode-gh/leetcode / shiftGrid

Method shiftGrid

java/1260-shift-2d-grid.java:3–25  ·  view source on GitHub ↗
(int[][] grid, int k)

Source from the content-addressed store, hash-verified

1class 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}

Callers

nothing calls this directly

Calls 3

addMethod · 0.45
setMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected