File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
2
+
3
+ In one shift operation:
4
+
5
+ Element at grid[i][j] moves to grid[i][j + 1].
6
+ Element at grid[i][n - 1] moves to grid[i + 1][0].
7
+ Element at grid[m - 1][n - 1] moves to grid[0][0].
8
+ Return the 2D grid after applying shift operation k times.
9
+
10
+
11
+
12
+ class Solution {
13
+ public:
14
+ vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
15
+ vector<int> oneD;
16
+ vector<vector<int>> ans;
17
+ int n=grid.size();
18
+ int m=grid[0].size();
19
+
20
+ for(int i=0; i<grid.size(); i++){
21
+ for(int j=0; j<grid[i].size(); j++){
22
+ oneD.push_back(grid[i][j]);
23
+ }
24
+ }
25
+
26
+
27
+ reverse(oneD.begin(), oneD.end());
28
+ reverse(oneD.begin(), oneD.begin()+ k % (n * m));
29
+ reverse(oneD.begin()+ k % (n * m), oneD.end());
30
+
31
+ int index=0;
32
+ for(int i=0; i<n; i++){
33
+ vector<int> row;
34
+ for(int j=0; j<m; j++){
35
+ row.push_back(oneD[index]);
36
+ index++;
37
+ }
38
+ ans.push_back(row);
39
+ }
40
+
41
+
42
+
43
+
44
+
45
+
46
+ return ans;
47
+
48
+
49
+ }
50
+ };
You can’t perform that action at this time.
0 commit comments