-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral Order Matrix I
55 lines (42 loc) · 1.03 KB
/
Spiral Order Matrix I
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
55
/*
Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example:
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return
[1, 2, 3, 6, 9, 8, 7, 4, 5]
*/
vector<int> Solution::spiralOrder(const vector<vector<int> > &A) {
vector<int> res;
int row1 = 0;
int col1 = 0;
int row2 = A.size()-1;
int col2 = A[0].size()-1;
while (row1 <= row2 && col1 <= col2){
for(int i = col1; i <= col2; ++i){
res.push_back(A[row1][i]);
}
row1++;
for(int i = row1; i <= row2; ++i){
res.push_back(A[i][col2]);
}
col2--;
if(row1 <= row2){
for(int i = col2; i >= col1; --i){
res.push_back(A[row2][i]);
}
row2--;
}
if(col1 <= col2){
for(int i = row2; i >= row1; --i){
res.push_back(A[i][col1]);
}
col1++;
}
}
return res;
}