-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy path0054.cpp
More file actions
40 lines (40 loc) · 834 Bytes
/
0054.cpp
File metadata and controls
40 lines (40 loc) · 834 Bytes
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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty() || matrix[0].empty()) {
return res;
}
int u = 0;
int d = matrix.size() - 1;
int l = 0;
int r = matrix[0].size() - 1;
while (true) {
for (int i = l; i <= r; ++i) {
res.emplace_back(matrix[u][i]);
}
if (++u > d) {
break;
}
for (int i = u; i <= d; ++i) {
res.emplace_back(matrix[i][r]);
}
if (--r < l) {
break;
}
for (int i = r; i >= l; --i) {
res.emplace_back(matrix[d][i]);
}
if (--d < u) {
break;
}
for (int i = d; i >= u; --i) {
res.emplace_back(matrix[i][l]);
}
if (++l > r) {
break;
}
}
return res;
}
};