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.
1using System;
2
3public class Solution {
4 public void Rotate(int[][] matrix) {
5 int n = matrix.Length;
6 for (int i = 0; i < n; i++) {
7 for (int j = i; j < n; j++) {
8 int temp = matrix[i][j];
9 matrix[i][j] = matrix[j][i];
10 matrix[j][i] = temp;
11 }
12 }
13 for (int i = 0; i < n; i++) {
14 Array.Reverse(matrix[i]);
15 }
16 }
17
18 public static void Main(string[] args) {
19 int[][] matrix = new int[3][] {
20 new int[] {1, 2, 3},
21 new int[] {4, 5, 6},
22 new int[] {7, 8, 9}
23 };
24 Solution sol = new Solution();
25 sol.Rotate(matrix);
26 foreach (var row in matrix) {
27 Console.WriteLine(string.Join(", ", row));
28 }
29 }
30}
This C# solution implements the transpose and reverse strategy using straightforward loops and the built-in Array.Reverse method.
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.
1#include <stdio.h>
2
3void rotate(int matrix[][3], int n) {
4 for (int layer = 0; layer < n / 2; layer++) {
5 int first = layer;
6 int last = n - layer - 1;
7 for (int i = first; i < last; i++) {
8 int offset = i - first;
9 int top = matrix[first][i];
10 matrix[first][i] = matrix[last - offset][first];
11 matrix[last - offset][first] = matrix[last][last - offset];
12 matrix[last][last - offset] = matrix[i][last];
13 matrix[i][last] = top;
14 }
15 }
16}
17
18int main() {
19 int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
20 rotate(matrix, 3);
21 for (int i = 0; i < 3; i++) {
22 for (int j = 0; j < 3; j++) {
23 printf("%d ", matrix[i][j]);
24 }
25 printf("\n");
26 }
27 return 0;
28}
The C solution processes the matrix in concentric layers, shifting each element appropriately to its new position during the 90-degree rotation.