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.
1import java.util.Arrays;
2
3class 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 for (int j = 0; j < n / 2; j++) {
15 int temp = matrix[i][j];
16 matrix[i][j] = matrix[i][n - j - 1];
17 matrix[i][n - j - 1] = temp;
18 }
19 }
20 }
21
22 public static void main(String[] args) {
23 Solution sol = new Solution();
24 int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
25 sol.rotate(matrix);
26 for (int[] row : matrix) {
27 System.out.println(Arrays.toString(row));
28 }
29 }
30}
The Java solution uses nested loops for transposing the matrix elements and another set of loops for reversing 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.
1#include <vector>
2#include <iostream>
3
4using namespace std;
5
6void rotate(vector<vector<int>>& matrix) {
7 int n = matrix.size();
8 for (int layer = 0; layer < n / 2; layer++) {
9 int first = layer;
10 int last = n - 1 - layer;
11 for (int i = first; i < last; i++) {
12 int offset = i - first;
13 int top = matrix[first][i];
14 matrix[first][i] = matrix[last - offset][first];
15 matrix[last - offset][first] = matrix[last][last - offset];
16 matrix[last][last - offset] = matrix[i][last];
17 matrix[i][last] = top;
18 }
19 }
20}
21
22int main() {
23 vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
24 rotate(matrix);
25 for (auto& row : matrix) {
26 for (int num : row) {
27 cout << num << " ";
28 }
29 cout << endl;
30 }
31 return 0;
32}
This approach processes the matrix layer by layer, swapping four elements at a time in a circular fashion to rotate the matrix.