-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
1-7-matrix-rotation.cpp
75 lines (64 loc) · 1.45 KB
/
1-7-matrix-rotation.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
74
75
#include<iostream>
void helper_transpose(int **matrix, int N)
{
for( int i = 0; i < N; ++i ) {
for( int j = i+1; j < N; ++j ) {
if ( i != j ) {
std::swap(matrix[i][j], matrix[j][i]);
}
}
}
}
void helper_reverse( int * row, int N ) {
for ( int i = 0; i < N/2; ++i ) {
std::swap(row[i], row[N-i-1]);
}
}
void rotate1(int ** matrix, int N) {
//transpose matrix
helper_transpose(matrix, N);
// reverse each row
for ( int i = 0; i < N; ++i ) {
helper_reverse(matrix[i], N);
}
}
void rotate2( int ** matrix, int N ) {
for( int i = 0; i < N/2; ++i ) {
for( int j = i; j < N-i-1; ++j ) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][N-i-1];
matrix[j][N-i-1] = matrix[N-i-1][N-j-1];
matrix[N-i-1][N-j-1]= matrix[N-j-1][i];
matrix[N-j-1][i] = temp;
}
}
}
void printMatrix( int ** matrix, int N) {
for ( int i = 0; i < N; ++i ) {
for( int j = 0; j < N; ++j ) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
int N;
std::cout << "Enter N for NxN matrix:";
std::cin >> N;
int ** matrix = new int*[N];
for ( int i = 0; i < N; ++i ) {
matrix[i] = new int[N];
}
for ( int i = 0; i < N; ++i) {
for ( int j = 0; j < N; ++j ) {
std::cin >> matrix[i][j];
}
}
std::cout << "Rotated matrix by 90 (clockwise):\n";
rotate1(matrix, N);
printMatrix(matrix, N);
std::cout << "Rotated matrix again by 90(anticlockwise):\n";
rotate2(matrix, N);
printMatrix(matrix, N);
return 0;
}