-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0054.cpp
51 lines (50 loc) · 1.11 KB
/
0054.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
46
47
48
49
50
51
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int n = matrix.size();
if (!n) {
return result;
}
vector<vector<bool>> visit;
initVisit(matrix, visit);
int m = matrix[0].size(), cnt = n * m, i = 0, j = 0;
while (cnt) {
while (j < m && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i][j ++] = true;
-- cnt;
}
-- j, ++ i;
while (i < n && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i ++][j] = true;
-- cnt;
}
-- i, -- j;
while (j >= 0 && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i][j --] = true;
-- cnt;
}
++ j, -- i;
while (i >= 0 && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i --][j] = true;
-- cnt;
}
++ i, ++ j;
}
return result;
}
void initVisit(vector<vector<int>>& matrix, vector<vector<bool>>& visit) {
int row = matrix.size(), column = matrix[0].size();
for (int i = 0; i < row; ++ i) {
vector<bool> temp;
for (int j = 0; j < column; ++ j) {
temp.push_back(false);
}
visit.push_back(temp);
}
}
};