垂直翻转子矩阵

题目描述1

题目讲解

确定子矩阵范围:

行范围:从 x 到 x + k - 1

列范围:从 y 到 y + k - 1

上下翻转:

使用双指针:top = x,bottom = x + k - 1

循环交换 grid[top][y..y+k-1] 和 grid[bottom][y..y+k-1]

每次交换后 top++,bottom–,直到完成。

返回结果:

具体流程

代码

c++
python
java
class Solution:
    def reverseSubmatrix(self, grid: List[List[int]], x: int, y: int, k: int) -> List[List[int]]:
        top, bottom = x, x + k - 1
        while top < bottom:
            # range(y, y+k): y->y+k-1.
            for j in range(y, y + k):
                grid[top][j], grid[bottom][j] = grid[bottom][j], grid[top][j]
            top += 1
            bottom -= 1
        return grid

链接