This approach utilizes two main operations. First, we transpose the matrix, which means flipping it over its diagonal. In other words, swap matrix[i][j] with matrix[j][i]. After transposing the matrix, we reverse each row. This combination results in a 90-degree clockwise rotation.
Time Complexity: O(n^2) - Because we loop through each element once.
Space Complexity: O(1) - No extra space is used, operations are in-place.
1#include <stdio.h>
2
3void rotate(int matrix[][3], int n) {
4 for (int i = 0; i < n; i++) {
5 for (int j = i; j < n; j++) {
6 int temp = matrix[i][j];
7 matrix[i][j] = matrix[j][i];
8 matrix[j][i] = temp;
9 }
10 }
11 for (int i = 0; i < n; i++) {
12 for (int j = 0; j < n/2; j++) {
13 int temp = matrix[i][j];
14 matrix[i][j] = matrix[i][n-j-1];
15 matrix[i][n-j-1] = temp;
16 }
17 }
18}
19
20int main() {
21 int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
22 rotate(matrix, 3);
23 for (int i = 0; i < 3; i++) {
24 for (int j = 0; j < 3; j++) {
25 printf("%d ", matrix[i][j]);
26 }
27 printf("\n");
28 }
29 return 0;
30}
The code first transposes the given matrix in place using two nested loops. Then, for each row, it reverses the elements to achieve a 90-degree clockwise rotation.
This approach rotates the matrix layer by layer or ring by ring. Start from the outer layer and move to the inner layer, rotating elements by moving them in groups of four. This involves swapping the elements in four-step rotations.
Time Complexity: O(n^2) - Each individual element is moved once.
Space Complexity: O(1) - Done entirely in place, without additional memory.
1function rotate(matrix) {
2 const n = matrix.length;
3 for (let layer = 0; layer < n / 2; layer++) {
4 let first = layer;
5 let last = n - 1 - layer;
6 for (let i = first; i < last; i++) {
7 let offset = i - first;
8 let top = matrix[first][i];
9 matrix[first][i] = matrix[last - offset][first];
10 matrix[last - offset][first] = matrix[last][last - offset];
11 matrix[last][last - offset] = matrix[i][last];
12 matrix[i][last] = top;
13 }
14 }
15}
16
17const matrix = [
18 [1, 2, 3],
19 [4, 5, 6],
20 [7, 8, 9]
21];
22rotate(matrix);
23console.log(matrix);
In JavaScript, the approach progresses through layers of the matrix, rotating each element of a layer by executing four swaps to achieve the 90-degree rotation.