Given a 2D grid of size n * m and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] becomes at grid[i][j + 1].
Element at grid[i][m - 1] becomes at grid[i + 1][0].
Element at grid[n - 1][m - 1] becomes at grid[0][0].
Return the 2D grid after applying shift operation k times.

 

Example 1:


Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:


Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
 

Constraints:

1 <= grid.length <= 50
1 <= grid[i].length <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shift-2d-grid
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我分两两步写的,

第一步向右循环转移 

第二步向下循环转移

class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int one = grid.size();
        int two = grid[0].size();
        
        int lun=k/two;
        lun=lun%one;
        k=k%two;
        vector<vector<int>>v;
        for(int i=0;i<one;i++){
            vector<int> vv(two);
            v.push_back(vv);
        }
        for(int i=0;i<one;i++){
            for(int j=0;j<two;j++){
                v[i][(j+k)%two]=grid[i][j];
            }
        }
        vector<vector<int>>v2;
        for(int i=0;i<one;i++){
            vector<int> vv2(two);
            v2.push_back(vv2);
        }
        for(int i=0;i<one;i++){
            for(int j=0;j<two;j++){
                if(j<k){
                    v2[(i+lun+1)%one][j]=v[i][j];
                }
                else{
                    v2[(i+lun)%one][j]=v[i][j];
                }
            }
        }
        return v2;
        
    }
};