-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiralOrder.cpp
45 lines (41 loc) · 1.27 KB
/
spiralOrder.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
#include <vector>
using namespace std;
#define BE_PRINTED -500
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size(); // m 行 n列
vector<int> results;
int x = 0, y = 0, cnt = 1;
results.push_back(matrix[x][y]);
matrix[x][y] = BE_PRINTED;
while (cnt < m * n)
{
// right
while (y < n - 1 && matrix[x][y + 1] != BE_PRINTED) {
results.push_back(matrix[x][++y]);
matrix[x][y] = BE_PRINTED;
cnt++;
}
// down
while (x < m - 1 && matrix[x + 1][y] != BE_PRINTED) {
results.push_back(matrix[++x][y]);
matrix[x][y] = BE_PRINTED;
cnt++;
}
// left
while (y > 0 && matrix[x][y - 1] != BE_PRINTED) {
results.push_back(matrix[x][--y]);
matrix[x][y] = BE_PRINTED;
cnt++;
}
// up
while (x > 0 && matrix[x - 1][y] != BE_PRINTED) {
results.push_back(matrix[--x][y]);
matrix[x][y] = BE_PRINTED;
cnt++;
}
}
return results;
}
};