Skip to content

Commit 8bee428

Browse files
authored
Merge pull request neetcode-gh#1786 from AP-Repositories/patch-52
Create 1260-shift-2d-grid.cpp
2 parents 64892b2 + c82c0fd commit 8bee428

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

cpp/1260-shift-2d-grid.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
4+
const int M = grid.size(), N = grid[0].size();
5+
6+
auto posToVal = [&] (int r, int c) -> int {
7+
return r * N + c;};
8+
auto valToPos = [&] (int v) -> int* {
9+
return new int[] {v / N, v % N};};
10+
11+
vector<vector<int>> res;
12+
for(int r = 0; r < M; r++) {
13+
vector<int> row;
14+
for(int c = 0; c < N; c++)
15+
row.push_back(0);
16+
res.push_back(row);
17+
}
18+
for(int r = 0; r < M; r++)
19+
for(int c = 0; c < N; c++) {
20+
int newVal = (posToVal(r, c) + k) % (M * N);
21+
int *newRC = valToPos(newVal);
22+
res[newRC[0]][newRC[1]] = grid[r][c];
23+
}
24+
return res;
25+
}
26+
};

0 commit comments

Comments
 (0)