-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate_image.cpp
73 lines (63 loc) · 1.73 KB
/
rotate_image.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// https://leetcode.com/problems/rotate-image/
// June 04, 2016
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void rotate(vector<vector<int> >& matrix)
{
unsigned int n = matrix.size();
// outer for loop: iterates layer by layer starting from outermost towards innermost
// inner for loop: rotates the element of the current layer
for (unsigned int i=0; i<(n/2); ++i)
{
for (unsigned int j=i; j < (n-1-i); ++j)
{
int elem1 = matrix[i][j];
// int elem2 = matrix[j][n-1-i];
// int elem3 = matrix[n-1-i][n-1-j];
// int elem4 = matrix[n-1-j][i];
// elem1->elem2->elem3->elem4->elem1
matrix[i][j] = matrix[n-1-j][i];
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
matrix[j][n-1-i] = elem1;
}
}
}
};
void display_matrix(vector<vector<int> >& matrix)
{
unsigned int n = matrix.size();
for (unsigned int i=0; i != n; ++i)
{
for (unsigned int j = 0; j != n; ++j)
{
cout << matrix[i][j] << ",";
}
cout << endl;
}
}
int main(int argc, char* argv)
{
vector<vector<int> > matrix;
int n = 6;
for (int i=0; i != n; ++i)
{
vector<int> vec;
for (int j=0; j != n; ++j)
{
vec.push_back(i*n+j);
}
matrix.push_back(vec);
}
cout << "Initial matrix: " << endl;
display_matrix(matrix);
cout << endl;
Solution sln;
sln.rotate(matrix);
cout << "Rotated matrix: " << endl;
display_matrix(matrix);
return 0;
}