Skip to content

Commit c578c91

Browse files
solves shift 2d grid
1 parent 6d4a8d4 commit c578c91

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@
326326
| 1237 | [Find Positive Integer Solutions for a Given Equation](https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation) | | |
327327
| 1243 | 🔒 [Array Transformation](https://leetcode.com/problems/array-transformation) | | |
328328
| 1252 | [Cells With Odd Values In Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix) | [![Java](assets/java.png)](src/CellsWithOddValuesInMatrix.java) | |
329-
| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid) | | |
329+
| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid) | [![Java](assets/java.png)](src/Shift2DGrid.java) | |
330330
| 1266 | [Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points) | | |
331331
| 1271 | [Hexspeak](https://leetcode.com/problems/hexspeak) | | |
332332
| 1275 | [Find Winner On a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game) | | |

src/Shift2DGrid.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class Shift2DGrid {
5+
public static List<List<Integer>> shiftGrid(int[][] grid, int k) {
6+
final int rows = grid.length, columns = grid[0].length;
7+
final List<List<Integer>> result = getGrid(rows, columns);
8+
final int rowOperations = k / columns;
9+
for (int column = 0 ; column < columns ; column++) {
10+
int rowShifts = (rowOperations + (k - columns * rowOperations - 1 >= column ? 1 : 0)) % rows;
11+
int columnIndex = (columns + column - (k % columns)) % columns;
12+
for (int row = 0 ; row < rows ; row++) {
13+
result.get(row).set(column, grid[(rows + row - rowShifts) % rows][columnIndex]);
14+
}
15+
}
16+
return result;
17+
}
18+
19+
private static List<List<Integer>> getGrid(int rows, int columns) {
20+
List<List<Integer>> result = new ArrayList<>(rows);
21+
for (int row = 0 ; row < rows ; row++) {
22+
result.add(getList(columns));
23+
}
24+
return result;
25+
}
26+
27+
private static List<Integer> getList(int size) {
28+
List<Integer> result = new ArrayList<>();
29+
for (int i = 0 ; i < size ; i++) {
30+
result.add(0);
31+
}
32+
return result;
33+
}
34+
}

0 commit comments

Comments
 (0)