-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54.cpp
58 lines (57 loc) · 1.45 KB
/
54.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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>> &matrix) {
enum Direction { Right, Down, Left, Up };
Direction current = Right;
vector<int> result;
int count = 0;
int currentUp = 0;
int currentRight = matrix[0].size() - 1;
int currentDown = matrix.size() - 1;
int currentLeft = 0;
int total = matrix[0].size() * matrix.size();
while (count < total) {
if (current == Right) {
int i = currentLeft;
while (count < total && i <= currentRight) {
count++;
result.push_back(matrix[currentUp][i]);
i++;
}
current = Down;
currentUp++;
}
if (current == Down) {
int i = currentUp;
while (count < total && i <= currentDown) {
count++;
result.push_back(matrix[i][currentRight]);
i++;
}
current = Left;
currentRight--;
}
if (current == Left) {
int i = currentRight;
while (count < total && i >= currentLeft) {
count++;
result.push_back(matrix[currentDown][i]);
i--;
}
current = Up;
currentDown--;
}
if (current == Up) {
int i = currentDown;
while (count < total && i >= currentUp) {
count++;
result.push_back(matrix[i][currentLeft]);
i--;
}
current = Right;
currentLeft++;
}
}
return result;
}
};