-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path48_rotate_matrix.cpp
46 lines (42 loc) · 909 Bytes
/
48_rotate_matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// LC - 48. Rotate Image
// You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
// TC - O(n^2)
// SC - O(1)
#include <bits/stdc++.h>
using namespace std;
void rotate(vector<vector<int>> &matrix) {
//transpose the arrays
for(int i =0; i<matrix.size(); i++){
for(int j =0; j<= i; j++){
swap(matrix[i][j], matrix[j][i]);
}
}
//reverse the arrays
for(int i = 0; i<matrix.size(); i++){
reverse(matrix[i].begin(), matrix[i].end());
}
}
int main() {
int n;
int m;
cin>>n;
cin >> m;
vector<vector<int>> matrix;
for(int i =0; i<n; i++){
vector<int> rows;
for(int j = 0; j<m; j++){
int a;
cin>> a;
rows.push_back(a);
}
matrix.push_back(rows);
}
rotate(matrix);
for(int i =0; i<n; i++) {
for(int j =0; j<m; j++){
cout<<matrix[i][j]<< " ";
}
cout<<endl;
}
return 0;
}