Skip to main content
Back to problems
#1914
Medium Algorithms

Cyclically rotating a grid

Array Matrix Simulation
51.6% acceptance
Feb 25, 2026
270
278
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn rotate_grid(grid: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
    let m = grid.len();
    let n = grid[0].len();
    let mut result = grid.clone();
    let layers = m.min(n) / 2;

    for layer in 0..layers {
      // Extract elements of this layer in order (top, right, bottom, left)
      let mut elements = Vec::new();
      let top = layer;
      let bottom = m - 1 - layer;
      let left = layer;
      let right = n - 1 - layer;

      // Top row left to right
      for j in left..=right {
        elements.push(grid[top][j]);
      }
      // Right column top+1 to bottom
      for i in (top + 1)..=bottom {
        elements.push(grid[i][right]);
      }
      // Bottom row right-1 to left
      for j in (left..right).rev() {
        elements.push(grid[bottom][j]);
      }
      // Left column bottom-1 to top+1
      for i in ((top + 1)..bottom).rev() {
        elements.push(grid[i][left]);
      }

      let len = elements.len();
      let rot = (k as usize) % len;

      // Place rotated elements back (counter-clockwise rotation = shift left)
      let mut idx = 0;
      for j in left..=right {
        result[top][j] = elements[(idx + rot) % len];
        idx += 1;
      }
      for i in (top + 1)..=bottom {
        result[i][right] = elements[(idx + rot) % len];
        idx += 1;
      }
      for j in (left..right).rev() {
        result[bottom][j] = elements[(idx + rot) % len];
        idx += 1;
      }
      for i in ((top + 1)..bottom).rev() {
        result[i][left] = elements[(idx + rot) % len];
        idx += 1;
      }
    }
    result
  }
}