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.
1def rotate(matrix):
2 n = len(matrix)
3 for i in range(n):
4 for j in range(i, n):
5 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
6 for i in range(n):
7 matrix[i].reverse()
8
9if __name__ == "__main__":
10 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
11 rotate(matrix)
12 for row in matrix:
13 print(row)
Transpose the matrix by swapping elements across the diagonal, followed by reversing each row in place using the built-in reverse method in Python.
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.
1class Solution {
2 public void rotate(int[][] matrix) {
3 int n = matrix.length;
4 for (int layer = 0; layer < n / 2; layer++) {
5 int first = layer;
6 int last = n - 1 - layer;
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
18 public static void main(String[] args) {
19 Solution sol = new Solution();
20 int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
21 sol.rotate(matrix);
22 for (int[] row : matrix) {
23 System.out.println(java.util.Arrays.toString(row));
24 }
25 }
26}
The Java solution iterates over each layer of the matrix, moving elements in a one-time shift to their new positions by rotating them four at a time.