Leetcode 1260. Shift 2D Grid Sure, let’s break down the process of solving the problem:
You are given a 2D grid of integers and an integer k
. You need to shift the grid k
times. In one shift operation:
You need to return the 2D grid after applying the shift operation k
times.
k
be larger than the number of elements in the grid?k % total number of elements
.#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int m = grid.size();
int n = grid[0].size();
int total = m * n;
k = k % total; // To handle cases where k is larger than the number of elements
if (k == 0) return grid;
// Step 1: Flatten the grid into a 1D array
vector<int> flattened(total);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
flattened[i * n + j] = grid[i][j];
}
}
// Step 2: Shift the flattened array
vector<int> newFlattened(total);
for (int i = 0; i < total; ++i) {
int newIndex = (i + k) % total;
newFlattened[newIndex] = flattened[i];
}
// Step 3: Convert the shifted 1D array back to the 2D grid form
vector<vector<int>> newGrid(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
newGrid[i][j] = newFlattened[i * n + j];
}
}
return newGrid;
}
};
int main() {
Solution sol;
vector<vector<int>> grid = \{\{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int k = 1;
vector<vector<int>> result = sol.shiftGrid(grid, k);
for (auto row : result) {
for (auto val : row) {
cout << val << " ";
}
cout << endl;
}
return 0;
}
The time complexity of this approach is O(m * n) where m
is the number of rows and n
is the number of columns in the grid. This is because we:
Hence, the overall time complexity remains O(m * n).
Would you like to proceed with more details on a particular step or another question?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?