-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_Rotate.cpp
More file actions
125 lines (92 loc) · 2.58 KB
/
matrix_Rotate.cpp
File metadata and controls
125 lines (92 loc) · 2.58 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
class Solution{
public:
void printMat(vector<vector <int>> matrix) {
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
}
void printVector(vector <int> vec) {
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
return;
}
void rotate(vector<vector <int>> & matrix) {
int Rows = matrix.size();
int Cols = matrix[0].size();
//cout << Rows << " " << Cols << endl;
int K = Rows / 2;
for (int k = 0; k < K; k++) {
int row = k ;
int col = k ;
for (int cnt = 0 ; cnt < Cols - 1 - (2*k); cnt++) {
int tempvalOne = matrix[row + cnt][Cols - 1 - k];
matrix[row +cnt ][Cols - 1 - k] = matrix[row][col + cnt];
int tempvalTwo = matrix[Rows - 1 - k][Cols - 1 - k - cnt ];
matrix[Rows - 1 - k][Cols - 1 - k -cnt ] = tempvalOne;
tempvalOne = matrix[Rows - 1 - k -cnt ][col];
matrix[Rows - 1 - k -cnt][col] = tempvalTwo;
matrix[row][col + cnt ] = tempvalOne;
}
}
printMat(matrix);
}
vector<int> spiralOrder(vector<vector<int>>& mat) {
int M = mat.size(), N = mat[0].size();
vector<int> result(M*N);
int rowStart = 0;
int rowEnd = M - 1;
int colStart = 0;
int colEnd = N - 1;
int cnt = 0;
while (rowStart <= rowEnd && colStart <= colEnd) {
// Horizontal From Left to Right
for (int col = colStart; col <= colEnd; col++) {
result[cnt++] = mat[rowStart][col];
}
if (++rowStart >rowEnd) break;
//Vertical Top to Bottom
for (int row = rowStart; row <= rowEnd; row++) {
result[cnt++] = mat[row][colEnd];
}
if (--colEnd<colStart) break;
//Horizontal Right to Left
for (int col = colEnd; col >= colStart; col--) {
result[cnt++] = mat[rowEnd][col];
}
if (--rowEnd < rowStart) break;
//vertical up from the left
for (int row = rowEnd; row >= rowStart; row--) {
result[cnt++] = mat[row][colStart];
}
if (++colStart > colEnd) break;
}
return result;
}
};
int main() {
int i = 9;
cout << (i >> 1) << endl;
exit(0);
vector<vector<int>> newmat(4, vector<int> (4));
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
newmat[i][j] = ++count;
}
}
//printMat(newmat);
Solution obj;
vector<int> res = obj.spiralOrder(newmat);
obj.printVector(res);
return 0;
}