LeetCode 54. 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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int left = 0;
int right = matrix[0].size() - 1;
int top = 0;
int bottom = matrix.size() - 1;
vector<int> ans;
while (true) {
for (int i = left; i <= right; ++i)
ans.push_back(matrix[top][i]);
if (++top > bottom) break;
for (int i = top; i <= bottom; ++i)
ans.push_back(matrix[i][right]);
if (--right < left) break;
for (int i = right; i >= left; --i)
ans.push_back(matrix[bottom][i]);
if (--bottom < top) break;
for (int i = bottom; i >= top; --i)
ans.push_back(matrix[i][left]);
if (++left > right) break;
}
return ans;
}
};