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 <vector>
2#include <iostream>
3
4using namespace std;
5
6void rotate(vector<vector<int>>& matrix) {
7 int n = matrix.size();
8 for (int i = 0; i < n; i++) {
9 for (int j = i; j < n; j++) {
10 swap(matrix[i][j], matrix[j][i]);
11 }
12 }
13 for (int i = 0; i < n; i++) {
14 reverse(matrix[i].begin(), matrix[i].end());
15 }
16}
17
18int main() {
19 vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
20 rotate(matrix);
21 for (auto& row : matrix) {
22 for (int num : row) {
23 cout << num << " ";
24 }
25 cout << endl;
26 }
27 return 0;
28}
This implementation transposes the matrix using nested loops for swapping. Then, each row is reversed using the standard library function reverse.
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.
1def rotate(matrix):
2 n = len(matrix)
3 for layer in range(n // 2):
4 first, last = layer, n - layer - 1
5 for i in range(first, last):
6 offset = i - first
7 top = matrix[first][i]
8 matrix[first][i] = matrix[last - offset][first]
9 matrix[last - offset][first] = matrix[last][last - offset]
10 matrix[last][last - offset] = matrix[i][last]
11 matrix[i][last] = top
12
13if __name__ == "__main__":
14 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
15 rotate(matrix)
16 for row in matrix:
17 print(row)
This Python code rotates the matrix by processing each layer starting from the outside towards the center, applying a four-way swap.