-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShift_2D_Grid.py
36 lines (29 loc) · 1.01 KB
/
Shift_2D_Grid.py
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
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int n=grid.size();
int m=grid[0].size();
vector<vector<int>> ans(n,vector<int>(m));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int newJ=(j+k)%m; // (j + numbers of columns added)%m
int newI=(i+(j+k)/m)%n; // (i + numbers of rows added)%n
ans[newI][newJ]=grid[i][j];
}
}
return ans;
}
};
# BRUTE FORCE APPROACH
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows = len(grid)
cols = len(grid[0])
for _ in range(k):
prev = grid[-1][-1]
for row in range(rows):
for col in range(cols):
temp = grid[row][col]
grid[row][col] = prev
prev = temp
return grid