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