Skip to content

1914. Cyclically Rotating a Grid

Description

You 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 is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:

Return the matrix after applying k cyclic rotations to it.

 

Example 1:

Input: grid = [[40,10],[30,20]], k = 1
Output: [[10,20],[40,30]]
Explanation: The figures above represent the grid at every state.

Example 2:

Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
Explanation: The figures above represent the grid at every state.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 2 <= m, n <= 50
  • Both m and n are even integers.
  • 1 <= grid[i][j] <=5000
  • 1 <= k <= 109

 

Solutions

Solution: Simulation

  • Time complexity: O(mnk)
  • Space complexity: O(mn)

 

JavaScript

js
/**
 * @param {number[][]} grid
 * @param {number} k
 * @return {number[][]}
 */
const rotateGrid = function (grid, k) {
  const m = grid.length;
  const n = grid[0].length;
  const maxLayer = Math.min(m, n) / 2;

  for (let layer = 0; layer < maxLayer; layer++) {
    const rows = m - layer * 2;
    const cols = n - layer * 2;
    const cells = rows * 2 + cols * 2 - 4;
    const steps = k % cells;

    for (let step = 1; step <= steps; step++) {
      const start = grid[layer][layer];

      for (let col = 1; col < cols; col++) {
        grid[layer][layer + col - 1] = grid[layer][layer + col];
      }
      for (let row = 1; row < rows; row++) {
        grid[layer + row - 1][layer + cols - 1] = grid[layer + row][layer + cols - 1];
      }
      for (let col = cols - 1; col > 0; col--) {
        grid[layer + rows - 1][layer + col] = grid[layer + rows - 1][layer + col - 1];
      }
      for (let row = rows - 1; row > 0; row--) {
        grid[layer + row][layer] = grid[layer + row - 1][layer];
      }
      grid[layer + 1][layer] = start;
    }
  }
  return grid;
};

Released under the MIT license