Skip to content

Commit 5e161f5

Browse files
committed
added shift 2D grid
1 parent 73ea26d commit 5e161f5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Matrix/Shift2DGrid.java

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package Matrix;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class Shift2DGrid {
7+
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
8+
int row = grid.length;
9+
int col = grid[0].length;
10+
11+
// Create temporary array of the same size in which we will add element in new position after k shifting.
12+
int[][] temp = new int[row][col];
13+
14+
// Solution Approach:
15+
// Assume if we convert given array into 1D Array then shift element to k positions and after shifting all the elements we will again convert 1D Array to our original dimension array.
16+
17+
// Logic for Finding current elements index in 1D Array after shifting K times :
18+
// For current element We will just find that what will be its index in 1D Array
19+
// After for New position in 1D Array we will shift it k times means we will add K in current index
20+
// And if new position in 1D Array gets increased by its total size, we will modulo it by 1D Array Size
21+
22+
for(int i = 0; i < row; i++) {
23+
for(int j = 0; j < col; j++) {
24+
25+
// (i * col) + j : will Give Index in 1D Array
26+
// (i * col) + j + k : Adding K means we will shift it k times
27+
// ((i * col) + j + k ) % (row * col) : modulo it by array size (row * col), if it exceeds the size
28+
int indexIn1DArray = ((i * col) + j + k ) % (row * col);
29+
30+
// Now Based on the 1D Array Index we will find its index in our temporary result array
31+
int tempRowIndex = indexIn1DArray / col; // Find the particular row
32+
int tempColIndex = indexIn1DArray % col; // Find the particular column
33+
temp[tempRowIndex][tempColIndex] = grid[i][j]; // Add Element at that new index in our temporary result array
34+
}
35+
}
36+
37+
// Prepare Result in List
38+
List<List<Integer>> result = new ArrayList<List<Integer>>();
39+
40+
for(int i = 0; i < row; i++) {
41+
List<Integer> list = new ArrayList<Integer>();
42+
for(int j = 0; j < col; j++) {
43+
list.add(temp[i][j]);
44+
}
45+
result.add(list);
46+
}
47+
48+
return result;
49+
}
50+
}

0 commit comments

Comments
 (0)