-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpirally traversing a matrix 01-08-24 POTD.cpp
54 lines (54 loc) · 1.39 KB
/
Spirally traversing a matrix 01-08-24 POTD.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
52
53
54
class Solution
{
public:
vector<int> spirallyTraverse(vector<vector<int>> &m)
{
int u = 0, d = m.size() - 1, l = 0, r = m[0].size() - 1;
bool H = true, F = true;
vector<int> ans;
while (u <= d && l <= r)
{
if (H)
{
if (F)
{
// going right
for (int i = l; i <= r; i++)
ans.push_back(m[u][i]);
u++;
H = false;
}
else
{
// going left
for (int i = r; i >= l; i--)
ans.push_back(m[d][i]);
d--;
H = false;
}
}
else
{
if (F)
{
// goin down
for (int i = u; i <= d; i++)
ans.push_back(m[i][r]);
r--;
H = true;
F = false;
}
else
{
// going up
for (int i = d; i >= u; i--)
ans.push_back(m[i][l]);
l++;
H = true;
F = true;
}
}
}
return ans;
}
};