-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathspiral_print.cpp
More file actions
40 lines (36 loc) · 1.13 KB
/
spiral_print.cpp
File metadata and controls
40 lines (36 loc) · 1.13 KB
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
#include <bits/stdc++.h>
using namespace std;
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int row=matrix.size();
int col=matrix[0].size();
int count=0;
int total=row*col;
int startrow=0;
int endrow=row-1;
int startcol=0;
int endcol=col-1;
vector<int>ans;
while(count<total){
for(int i=startcol;i<=endcol && count<total;i++){
ans.push_back(matrix[startrow][i]);
count++;
}
startrow++;
for(int i=startrow;i<=endrow && count<total;i++){
ans.push_back(matrix[i][endcol]);
count++;
}
endcol--;
for(int i=endcol;i>=startcol && count<total;i--){
ans.push_back(matrix[endrow][i]);
count++;
}
endrow--;
for(int i=endrow;i>=startrow && count<total;i--){
ans.push_back(matrix[i][startcol]);
count++;
}
startcol++;
}
return ans;
}