Problem Statement
Given a square matrix of size N x N
, the task it to rotate the matrix by 90 degree clockwise. This means that each element of the matrix should be moved in a new position such that the rows become columns, and the order of elements in row is reversed.
LeetCode
Examples
Example 1:
Input: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output: matrix = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
Explanation:
1 2 3
4 5 6
7 8 9
is rotated 90 degree to right (clockwise)
will turn it into following:
7 4 1
8 5 2
9 6 3
Example 1:
Input: matrix = [
[0, 1, 1, 2],
[2, 0, 3, 1],
[4, 5, 0, 5],
[5, 6, 7, 0]
]
Output: [
[5, 4, 2, 0],
[6, 5, 0, 1],
[7, 0, 3, 1],
[0, 5, 1, 2]
]
Different Approaches
1️⃣ Brute Force Approach
Take another matrix of same size and then take the first row of the matrix and put it in the last column of the dummy matrix, take the second row of the matrix, and put it in the second last column of the matrix and so on.
Algorithm:
- Transpose the matrix (transposing means changing column to rows and rows to columns).
- Reverse each row of the matrix.
Dry Run:
Initialization:
+-----+-----+-----+
matrix = | 1 | 2 | 3 |
+-----+-----+-----+
| 4 | 5 | 6 |
+-----+-----+-----+
| 7 | 8 | 9 |
+-----+-----+-----+
Transpose:
+-----+-----+-----+
matrix = | 1 | 4 | 7 |
+-----+-----+-----+
| 2 | 5 | 8 |
+-----+-----+-----+
| 3 | 6 | 9 |
+-----+-----+-----+
Reverse Every Row:
+-----+-----+-----+
matrix = | 7 | 4 | 1 |
+-----+-----+-----+
| 8 | 5 | 2 |
+-----+-----+-----+
| 9 | 6 | 3 |
+-----+-----+-----+

Code:
#include<bits/stdc++.h>
using namespace std;
void rotate(vector < vector < int >> & matrix) {
int n = matrix.size();
//transposing the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
//reversing each row of the matrix
for (int i = 0; i < n; i++) {
reverse(matrix[i].begin(), matrix[i].end());
}
}
int main() {
vector < vector < int >> arr;
arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
rotate(arr);
cout << "Rotated Image" << endl;
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[0].size(); j++) {
cout << arr[i][j] << " ";
}
cout << "n";
}
}
Complexity Analysis:
- Time Complexity:
O(N * N )
+O(N * N)
- One
O(N * N)
is for transposing. - Other for reversing the matrix.
- One
- Space Complexity:
O(1)