Problem
1260. Shift 2D Grid
Code
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int total_rows = grid.size();
int total_cols = grid[0].size();
int length = total_rows * total_cols;
vector<vector<int>> shifted(total_rows, vector<int>(total_cols, 0));
for (int row = 0; row < total_rows; row++) {
for (int col = 0; col < total_cols; col++) {
int new_index =
((total_cols * row + col) + k) % (total_rows * total_cols);
int new_row, new_col;
new_row = (new_index / total_cols);
new_col = (new_index % total_cols);
shifted[new_row][new_col] = grid[row][col];
}
}
return shifted;
}
};
Logic
- Flattening logic:
index = total_cols * row + col
- Rotation logic:
new_index = (index + k) % length
- Unflattening logic:
new_row = index / total_cols and new_col = index % total_cols