[LeetCode] Cyclically Rotating a Grid

1914. Cyclically Rotating a Grid

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
void internal_swap(vector<vector<int>>& g, int start, int m, int n) {
for(int i = start; i < n - 1; i++) {
swap(g[start][i], g[start][i + 1]);
}
for(int i = start; i < m - 1; i++) {
swap(g[i][n - 1], g[i + 1][n - 1]);
}
for(int i = n - 1; i > start; i--) {
swap(g[m - 1][i], g[m - 1][i - 1]);
}
for(int i = m - 1; i > start + 1; i--) {
swap(g[i][start], g[i - 1][start]);
}
}
public:
vector<vector<int>> rotateGrid(vector<vector<int>>& grid, int k) {
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < min(m / 2, n / 2); i++) {
int cnt = k % (((n - (i * 2)) * 2) + (((m - ((i + 1) * 2))*2)));
for(int j = 0; j < cnt; j++)
internal_swap(grid, i, n - i, m - i);
}
return grid;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/27/PS/LeetCode/cyclically-rotating-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.