-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54. Spiral Matrix
43 lines (37 loc) · 1.16 KB
/
54. Spiral Matrix
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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows= matrix.size();
int cols= matrix[0].size();
vector<int> ans;
int count=0;
int length= rows*cols;
int startrow= 0;
int startcol=0;
int endrow= rows-1;
int endcol= cols-1;
while(count <length){
for(int i=startcol; count <length && i<=endcol; i++){
ans.push_back(matrix[startrow][i]);
count++;
}
startrow++;
for(int i=startrow; count <length && i<=endrow; i++){
ans.push_back(matrix[i][endcol]);
count++;
}
endcol--;
for(int i=endcol; count <length && i>= startcol;i--){
ans.push_back(matrix[endrow][i]);
count++;
}
endrow--;
for(int i=endrow; count <length && i>= startrow;i--){
ans.push_back(matrix[i][startcol]);
count++;
}
startcol++;
}
return ans;
}
};