---
# System prepended metadata

title: LeetCode - 1260. Shift 2D Grid
tags: [LeetCode]

---

---
title: LeetCode - 1260. Shift 2D Grid
tags: LeetCode
description: by cpp
---
# [LeetCode] 1260. Shift 2D Grid
input : **grid** 2d grid,**k** shift times
ouput : shift後的**grid**
這題會給一個陣列，要回傳他往後移幾次的陣列
![](https://i.imgur.com/ryBqq8L.png)

```cpp=
class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int row = grid.size();
        int col = grid[0].size();
        //把重複跳的部分取餘數
        k = k%(row*col);
        
        vector<vector<int>> result;
        //先把全部的數字存到nums，再把它分到結果陣列(也可以直接傳結果)
        vector<int> nums;
        vector<int> temp;
        int index=0;
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                nums.push_back(grid[i][j]);
            }
        }

        //依跳的次數填入結果陣列，可以畫圖比較容易理解
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                index = i*col+j-k;
                if(index<0){
                    temp.push_back(nums[index+row*col]);
                }else{
                    temp.push_back(nums[index]);
                }
                
            }
            result.push_back(temp);
            temp.clear();
        }
        
        return result;
    }
};

```
![](https://i.imgur.com/9kFyzPq.png)



{%hackmd theme-dark %}