LC 1260. Shift 2D Grid

Nilanjan Deb · April 28, 2020

This is my CPP solution.

class Solution {
private:
    void rotate(vector<int>& nums, int k) {
        int t[100200],n=nums.size();
        k = k%n;
        for(int i=0;i<n;i++){
            if(i>=n-k){
                t[i+k-n] = nums[i];
            }
            else{
                t[i+k] = nums[i];
            }
        }
        nums.clear();
        for(int i=0;i<n;i++){
            nums.push_back(t[i]);
        }
    }
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        vector<int> store;
        int n = grid.size(), m = grid[0].size(), cnt =0;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                store.push_back(grid[i][j]);
            }
        }
        rotate(store, k);
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                grid[i][j] = store[cnt++];
            }
        }
        return grid;
    }
};


Dicussion Forum