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
This function reverses a k×k submatrix within a grid by swapping elements symmetrically from opposite rows. Starting at coordinates (x, y), it iterates through the top half of the submatrix (k / 2 rows) and for each position, it swaps the value in the current row with its mirror position in the opposite row (calculated as k - 1 - row). The loop processes all k columns for each row pair, effectively flipping the submatrix vertically while keeping the grid structure intact. The swap operation uses a temporary variable to exchange values without data loss.
/**
* @param {number[][]} grid
* @param {number} x
* @param {number} y
* @param {number} k
* @return {number[][]}
*/
var reverseSubmatrix = function(grid, x, y, k) {
const rows = k / 2;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < k; col++) {
const inv_row = k - 1 - row;
if (row !== inv_row) {
const temp = grid[x + row][y + col];
grid[x + row][y + col] = grid[x + inv_row][y + col];
grid[x + inv_row][y + col] = temp;
}
}
}
return grid;
};