Repository navigation
Expand file tree
/
Copy pathrotateMatrix90degrees.cpp
More file actions
106 lines (69 loc) · 2.34 KB
/
Copy pathrotateMatrix90degrees.cpp
File metadata and controls
106 lines (69 loc) · 2.34 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cassert>
#include <set>
using namespace std;
/*
| QUESTION 1.6: Rotate a matrix 90 degrees.
|
| APPROACH: While and for loop combined, rotate one cell from each side at a time. At first, I tried
| rotating the entire row and column, but it didn't work out and the code was much much
| longer than this. I tried a total of 3 approaches and I found this one to be the easiest
| to understand and the most efficient one as well.
*/
const int SIZE = 5;
void printMatrix(int array[][SIZE]){
// --> prints the matrix
for(int i =0; i<SIZE; i++){
for(int m =0; m<SIZE; m++){
cout<< array[i][m]<<" ";
}
cout<<endl;
}
cout<<endl;
}
void initializeMatrix(int array[][SIZE]){
// --> set the whole matrix equal to 1
int index = 10;
for(int i =0; i<SIZE; i++){
for(int m =0; m<SIZE; m++){
array[i][m] = index;
index++;
}
}
}
void printArray(int * array, int limit){
for(int i=0; i<limit; i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
int main() {
int matrix[SIZE][SIZE];
initializeMatrix(matrix);
cout<<"Original Matrix:"<<endl;
printMatrix(matrix);
int array[SIZE-1]; //--> array of 4
int start_bound = 0;
int end_bound = SIZE-1;
cout<<endl;
int cycle = 0;
while(start_bound < end_bound){
cout<<"--- Cycle: "<<cycle<<" ---"<<endl;
int limit = end_bound - start_bound;
for(int i =0; i< limit; i++){
int temp = matrix[start_bound + i][start_bound]; //--> saving left column
matrix[start_bound + i][start_bound] = matrix[start_bound][end_bound -i]; // top -> left
matrix[start_bound][end_bound -i] = matrix[end_bound -i][end_bound];// right->top
matrix[end_bound -i ][end_bound] = matrix[end_bound][start_bound + i]; // bottom->right
matrix[end_bound][start_bound + i] = temp; // left/temp -> bottom
}
cycle++;
printMatrix(matrix);
start_bound++;
end_bound--;
}
return 0;
}