-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiral-order.cpp
46 lines (38 loc) · 1.2 KB
/
spiral-order.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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty() || matrix[0].empty()) {
return result;
}
int rows = matrix.size();
int cols = matrix[0].size();
int up = 0;
int down = rows - 1;
int pre = 0;
int next = cols - 1;
while (up <= down && pre <= next) {
for (int col = pre; col <= next; col++) {
result.push_back(matrix[up][col]);
}
up++;
for (int row = up; row <= down; row++) {
result.push_back(matrix[row][next]);
}
next--;
if (up <= down) {
for (int col = next; col >= pre; col--) {
result.push_back(matrix[down][col]);
}
down--;
}
if (pre <= next) {
for (int row = down; row >= up; row--) {
result.push_back(matrix[row][pre]);
}
pre++;
}
}
return result;
}
};