-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsolution.java
More file actions
49 lines (36 loc) · 1.29 KB
/
Copy pathsolution.java
File metadata and controls
49 lines (36 loc) · 1.29 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
// Get the grid dimensions
int m = grid.length;
int n = grid[0].length;
// Total number of elements
int total = m * n;
// Ignore unnecessary complete rotations
k %= total;
// Create the answer grid
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < m; i++) {
List<Integer> row = new ArrayList<>();
// Fill with dummy values so we can use set()
for (int j = 0; j < n; j++) {
row.add(0);
}
ans.add(row);
}
// Move every element to its final position
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Flatten the current position
int oldIndex = i * n + j;
// Compute shifted position
int newIndex = (oldIndex + k) % total;
// Convert back to row and column
int newRow = newIndex / n;
int newCol = newIndex % n;
// Store the value
ans.get(newRow).set(newCol, grid[i][j]);
}
}
return ans;
}
}