[Geeks for Geeks] Rotate a 2D array without using extra space

Rotate a 2D array without using extra space

Given a N x N 2D matrix Arr representing an image. Rotate the image by 90 degrees (anti-clockwise). You need to do this in place. Note that if you end up using an additional array, you will only receive partial score.

  • Time : O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution{
void helper(vector<vector<int>>& arr, int n, int start) {
if(n <= 1) return;
int y = start, x = start;
for(int i = 0; i < n - 1; i++) {
int tmp = arr[y][x + i];
arr[y][x + i] = arr[y + i][x + n - 1];
arr[y + i][x + n - 1] = arr[y + n - 1][x + n - 1 - i];
arr[y + n - 1][x + n - 1 - i] = arr[y + n - 1 - i][x];
arr[y + n - 1 - i][x] = tmp;
}

helper(arr, n - 2, start + 1);
}
public:
void rotateMatrix(vector<vector<int>>& arr, int n) {
helper(arr, n, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/rotate-a-2d-array-without-using-extra-space/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.