<p>Given a 2D <code>grid</code> of size <code>m x n</code>&nbsp;and an integer <code>k</code>. You need to shift the <code>grid</code>&nbsp;<code>k</code> times.</p>

<p>In one shift operation:</p>

<ul>
	<li>Element at <code>grid[i][j]</code> moves to <code>grid[i][j + 1]</code>.</li>
	<li>Element at <code>grid[i][n - 1]</code> moves to <code>grid[i + 1][0]</code>.</li>
	<li>Element at <code>grid[m&nbsp;- 1][n - 1]</code> moves to <code>grid[0][0]</code>.</li>
</ul>

<p>Return the <em>2D grid</em> after applying shift operation <code>k</code> times.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/11/05/e1.png" style="width: 400px; height: 178px;" />
<pre>
<strong>Input:</strong> <code>grid</code> = [[1,2,3],[4,5,6],[7,8,9]], k = 1
<strong>Output:</strong> [[9,1,2],[3,4,5],[6,7,8]]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/11/05/e2.png" style="width: 400px; height: 166px;" />
<pre>
<strong>Input:</strong> <code>grid</code> = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
<strong>Output:</strong> [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> <code>grid</code> = [[1,2,3],[4,5,6],[7,8,9]], k = 9
<strong>Output:</strong> [[1,2,3],[4,5,6],[7,8,9]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m ==&nbsp;grid.length</code></li>
	<li><code>n ==&nbsp;grid[i].length</code></li>
	<li><code>1 &lt;= m &lt;= 50</code></li>
	<li><code>1 &lt;= n &lt;= 50</code></li>
	<li><code>-1000 &lt;= grid[i][j] &lt;= 1000</code></li>
	<li><code>0 &lt;= k &lt;= 100</code></li>
</ul>

# 注意：python 代码由 chatGPT\U0001f916 根据我的 java 代码翻译，旨在帮助不同背景的读者理解算法逻辑。
# 本代码已经通过力扣的测试用例，应该可直接成功提交。

class Solution:
    def shiftGrid(self, grid, k):
        # 把二维 grid 抽象成一维数组
        m, n = len(grid), len(grid[0])
        mn = m * n
        k = k % mn
        # 先把最后 k 个数翻转
        self.reverse(grid, mn - k, mn - 1)
        # 然后把前 mn - k 个数翻转
        self.reverse(grid, 0, mn - k - 1)
        # 最后把整体翻转
        self.reverse(grid, 0, mn - 1)

        # 转化成 Java List
        res = []
        for row in grid:
            rowList = []
            for e in row:
                rowList.append(e)
            res.append(rowList)
        return res

    # 通过一维数组的索引访问二维数组的元素
    def get(self, grid, index):
        n = len(grid[0])
        i, j = divmod(index, n)
        return grid[i][j]

    # 通过一维数组的索引修改二维数组的元素
    def set(self, grid, index, val):
        n = len(grid[0])
        i, j = divmod(index, n)
        grid[i][j] = val

    # 翻转一维数组的索引区间元素
    def reverse(self, grid, i, j):
        while i < j:
            temp = self.get(grid, i)
            self.set(grid, i, self.get(grid, j))
            self.set(grid, j, temp)
            i += 1
            j -= 1
17000