---
# System prepended metadata

title: Leetcode 1260. Shift 2D Grid

---

# Leetcode 1260. Shift 2D Grid

## 二維矩陣展平 (Flatten Martix)

```python=
class Solution:
    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
        rows = len(grid)
        cols = len(grid[0])
        
        if rows * cols == k:
            return grid
        
        output = [[0 for _ in range(cols)] for _ in range(rows)]

        for node in range(rows * cols):
            x = node // cols
            y = node % cols
            pos = (node + k) % (rows * cols)
            new_x = pos // cols
            new_y = pos % cols
            output[new_x][new_y] = grid[x][y]
        
        return output
```
