3643. Flip Square Submatrix Vertically
March 17, 2026 · View on GitHub
Description
You are given an m x n integer matrix grid, and three integers x, y, and k.
The integers x and y represent the row and column indices of the top-left corner of a square submatrix and the integer k represents the size (side length) of the square submatrix.
Your task is to flip the submatrix by reversing the order of its rows vertically.
Return the updated matrix.
Example 1:
Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], x = 1, y = 0, k = 3
Output: [[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]
Explanation:
The diagram above shows the grid before and after the transformation.
Example 2:
Input: grid = [[3,4,2,3],[2,3,4,2]], x = 0, y = 2, k = 2
Output: [[3,4,4,2],[2,3,2,3]]
Explanation:
The diagram above shows the grid before and after the transformation.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 501 <= grid[i][j] <= 1000 <= x < m0 <= y < n1 <= k <= min(m - x, n - y)
Solutions
Solution 1: Simulation
We start from row and flip a total of rows.
For each row , we need to swap it with the corresponding row , where .
During the swap, we need to traverse and swap with .
Finally, return the updated matrix.
The time complexity is , where is the side length of the submatrix. The space complexity is .
Python3
class Solution:
def reverseSubmatrix(
self, grid: List[List[int]], x: int, y: int, k: int
) -> List[List[int]]:
for i in range(x, x + k // 2):
i2 = x + k - 1 - (i - x)
for j in range(y, y + k):
grid[i][j], grid[i2][j] = grid[i2][j], grid[i][j]
return grid
Java
class Solution {
public int[][] reverseSubmatrix(int[][] grid, int x, int y, int k) {
for (int i = x; i < x + k / 2; i++) {
int i2 = x + k - 1 - (i - x);
for (int j = y; j < y + k; j++) {
int t = grid[i][j];
grid[i][j] = grid[i2][j];
grid[i2][j] = t;
}
}
return grid;
}
}
C++
class Solution {
public:
vector<vector<int>> reverseSubmatrix(vector<vector<int>>& grid, int x, int y, int k) {
for (int i = x; i < x + k / 2; i++) {
int i2 = x + k - 1 - (i - x);
for (int j = y; j < y + k; j++) {
swap(grid[i][j], grid[i2][j]);
}
}
return grid;
}
};
Go
func reverseSubmatrix(grid [][]int, x int, y int, k int) [][]int {
for i := x; i < x+k/2; i++ {
i2 := x + k - 1 - (i - x)
for j := y; j < y+k; j++ {
grid[i][j], grid[i2][j] = grid[i2][j], grid[i][j]
}
}
return grid
}
TypeScript
function reverseSubmatrix(grid: number[][], x: number, y: number, k: number): number[][] {
for (let i = x; i < x + Math.floor(k / 2); i++) {
const i2 = x + k - 1 - (i - x);
for (let j = y; j < y + k; j++) {
[grid[i][j], grid[i2][j]] = [grid[i2][j], grid[i][j]];
}
}
return grid;
}
Rust
impl Solution {
pub fn reverse_submatrix(
mut grid: Vec<Vec<i32>>,
x: i32,
y: i32,
k: i32,
) -> Vec<Vec<i32>> {
let x = x as usize;
let y = y as usize;
let k = k as usize;
for i in x..(x + k / 2) {
let i2 = x + k - 1 - (i - x);
for j in y..(y + k) {
let t = grid[i][j];
grid[i][j] = grid[i2][j];
grid[i2][j] = t;
}
}
grid
}
}