-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotateMatrix.cpp
64 lines (57 loc) · 1.59 KB
/
rotateMatrix.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
#include <climits>
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int n = 4;
unordered_map<int, int> map;
int newPos[2];
int startPos[2];
int temp = INT_MIN;
bool switched(unordered_map<int, int>::iterator start,
unordered_map<int, int>::iterator end, int row, int col) {
for (auto i = start; i != end; i++) {
if (i->first == row && i->second == col) return true;
}
return false;
}
int* correctPos(int pos[]) {
newPos[0] = pos[1];
newPos[1] = n + 1 - pos[0];
return &newPos[0];
}
void changePos(vector<vector<int>>& matrix, int* pos, int* newPos) {
while (startPos != newPos) {
cout << pos[0] << " " << pos[1] << " " << newPos[0] << " " << newPos[1]
<< endl;
if (temp == INT_MIN) {
temp = matrix[newPos[0]][newPos[1]];
matrix[newPos[0]][newPos[1]] = matrix[pos[0]][pos[1]];
} else {
int buf = matrix[newPos[0]][newPos[1]];
matrix[newPos[0]][newPos[1]] = temp;
temp = buf;
}
map.insert({pos[0], pos[1]});
pos[0] = newPos[0], pos[1] = newPos[1];
correctPos(newPos);
}
}
int main() {
vector<vector<int>> matrix = {
{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
if (switched(map.begin(), map.end(), row, col)) continue;
startPos[0] = row, startPos[1] = col;
changePos(matrix, startPos, correctPos(startPos));
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}