Created
May 9, 2026 17:43
-
-
Save tatsuyax25/55d5f89d1b44ee0e89e1e897df85d88f to your computer and use it in GitHub Desktop.
ou are given an m x n integer matrix grid, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[][]} grid | |
| * @param {number} k | |
| * @return {number[][]} | |
| */ | |
| var rotateGrid = function(grid, k) { | |
| const m = grid.length, n = grid[0].length; | |
| const layers = Math.min(m, n) / 2; | |
| for (let layer = 0; layer < layers; layer++) { | |
| let ring = []; | |
| let top = layer, bottom = m - layer - 1; | |
| let left = layer, right = n - layer - 1; | |
| // top row | |
| for (let j = left; j <= right; j++) ring.push(grid[top][j]); | |
| // right col | |
| for (let i = top + 1; i <= bottom; i++) ring.push(grid[i][right]); | |
| // bottom row | |
| for (let j = right - 1; j >= left; j--) ring.push(grid[bottom][j]); | |
| // left col | |
| for (let i = bottom - 1; i > top; i--) ring.push(grid[i][left]); | |
| const L = ring.length; | |
| const kmod = k % L; | |
| const rotated = ring.slice(kmod).concat(ring.slice(0, kmod)); | |
| let idx = 0; | |
| // write back: top row | |
| for (let j = left; j <= right; j++) grid[top][j] = rotated[idx++]; | |
| // right col | |
| for (let i = top + 1; i <= bottom; i++) grid[i][right] = rotated[idx++]; | |
| // bottom row | |
| for (let j = right - 1; j >= left; j--) grid[bottom][j] = rotated[idx++]; | |
| // left col | |
| for (let i = bottom - 1; i > top; i--) grid[i][left] = rotated[idx++]; | |
| } | |
| return grid; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment