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.
1function rotate(matrix) {
2 const n = matrix.length;
3 for (let i = 0; i < n; i++) {
4 for (let j = i; j < n; j++) {
5 [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
6 }
7 }
8 for (let i = 0; i < n; i++) {
9 matrix[i].reverse();
10 }
11}
12
13const matrix = [
14 [1, 2, 3],
15 [4, 5, 6],
16 [7, 8, 9]
17];
18rotate(matrix);
19console.log(matrix);
Utilizes destructuring assignment for transposing elements and uses the Array.reverse function to flip the sequences of each row.
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.
1using System;
2
3public class Solution {
4 public void Rotate(int[][] matrix) {
5 int n = matrix.Length;
6 for (int layer = 0; layer < n / 2; layer++) {
7 int first = layer;
8 int last = n - 1 - layer;
9 for (int i = first; i < last; i++) {
10 int offset = i - first;
11 int top = matrix[first][i];
12 matrix[first][i] = matrix[last - offset][first];
13 matrix[last - offset][first] = matrix[last][last - offset];
14 matrix[last][last - offset] = matrix[i][last];
15 matrix[i][last] = top;
16 }
17 }
18 }
19
20 public static void Main(string[] args) {
21 int[][] matrix = new int[3][] {
22 new int[] {1, 2, 3},
23 new int[] {4, 5, 6},
24 new int[] {7, 8, 9}
25 };
26 Solution sol = new Solution();
27 sol.Rotate(matrix);
28 foreach (var row in matrix) {
29 Console.WriteLine(string.Join(", ", row));
30 }
31 }
32}
The C# solution advances through the matrix layer by layer, utilizing four swaps to adjust the elements to their rotated positions.