-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path54-spiral-matrix.cpp
41 lines (34 loc) · 1.13 KB
/
54-spiral-matrix.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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0) return {};
int r_beg = 0;
int r_end = matrix.size() - 1;
int c_beg = 0;
int c_end = matrix[0].size() - 1;
vector<int> result;
while (r_beg <= r_end && c_beg <= c_end) {
for (int i = c_beg; i <= c_end; i++) {
result.push_back(matrix[r_beg][i]);
}
r_beg++;
for (int i = r_beg; i <= r_end; i++) {
result.push_back(matrix[i][c_end]);
}
c_end--;
if (r_beg <= r_end) {
for (int i = c_end; i >= c_beg; i--) {
result.push_back(matrix[r_end][i]);
}
}
r_end--;
if (c_beg <= c_end) {
for (int i = r_end; i >= r_beg; i--) {
result.push_back(matrix[i][c_beg]);
}
}
c_beg++;
}
return result;
}
};