-
Notifications
You must be signed in to change notification settings - Fork 1
/
SpiralMatrix.cpp
47 lines (38 loc) · 1.13 KB
/
SpiralMatrix.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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(!matrix.size())
return {};
int i, dir = 0, T = 0, B = matrix.size() - 1, L = 0, R = matrix[0].size() - 1;
vector<int> ans;
while(T <= B && L <= R)
{
if(dir == 0)
{
for(i = L; i <= R; i++)
ans.push_back(matrix[T][i]);
T++;
}
else if(dir == 1)
{
for(i = T; i <= B; i++)
ans.push_back(matrix[i][R]);
R--;
}
else if(dir == 2)
{
for(i = R; i >= L; i--)
ans.push_back(matrix[B][i]);
B--;
}
else
{
for(i = B; i >= T; i--)
ans.push_back(matrix[i][L]);
L++;
}
dir = (dir + 1) % 4;
}
return ans;
}
};