-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix
34 lines (34 loc) · 986 Bytes
/
Spiral Matrix
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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = m ? matrix[0].size() : 0, u = 0, d = m - 1, l = 0, r = n - 1, p = 0;
vector<int> order(m * n);
while (u <= d && l <= r) {
for (int col = l; col <= r; col++) {
order[p++] = matrix[u][col];
}
if (++u > d) {
break;
}
for (int row = u; row <= d; row++) {
order[p++] = matrix[row][r];
}
if (--r < l) {
break;
}
for (int col = r; col >= l; col--) {
order[p++] = matrix[d][col];
}
if (--d < u) {
break;
}
for (int row = d; row >= u; row--) {
order[p++] = matrix[row][l];
}
if (l++ > r) {
break;
}
}
return order;
}
};