1260. Shift 2D Grid

问题
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.

遍历整个数组,将索引值加上移动的次数,得到新的位置。

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) {
List<List<Integer>> ans = new ArrayList<>();
int row = grid.length;
int col = grid[0].length;
int size = row * col;
Integer[][] mat = new Integer[row][col];

for (int i = 0; i < size; i++){
int j = i + k;
if ( j > size - 1){
j %= size;
}
int nr = j / col;
int nc = j % col;
int or = i / col;
int oc = i % col;

mat[nr][nc] = grid[or][oc];
}

for (int i = 0; i < row; i++){
List<Integer> nums = Arrays.asList(mat[i]);
ans.add(nums);
}

return ans;
}
}
Author

Xander

Posted on

2022-04-11

Updated on

2022-04-10

Licensed under

Comments