-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day109.cpp
47 lines (37 loc) · 972 Bytes
/
Day109.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
// Spiral Order Matrix I
// https://www.interviewbit.com/problems/spiral-order-matrix-i/
vector<int> Solution::spiralOrder(const vector<vector<int> > &A) {
int m = A.size();
int n = A[0].size();
vector<int> ans;
int rs = 0, cs = 0;
int re = m - 1;
int ce = n - 1;
while (rs <= re && cs <= ce) {
// Traverse right
for (int i = cs; i <= ce; i++) {
ans.push_back(A[rs][i]);
}
rs++;
// Traverse down
for (int i = rs; i <= re; i++) {
ans.push_back(A[i][ce]);
}
ce--;
if (rs <= re) {
// Traverse left
for (int i = ce; i >= cs; i--) {
ans.push_back(A[re][i]);
}
re--;
}
if (cs <= ce) {
// Traverse up
for (int i = re; i >= rs; i--) {
ans.push_back(A[i][cs]);
}
cs++;
}
}
return ans;
}