forked from ShreyaDhir/HacktoberFest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralMatrix.cpp
32 lines (30 loc) · 889 Bytes
/
SpiralMatrix.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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> v;
int i, k=0,l=0;
int r= matrix.size();
if(r==0) return v;
int m=r-1;
int c=r?matrix[0].size():0;
int n=c-1;
while(k<=m && l<=n)
{
for(i=l;i<=n;i++) //l is the column start index, n is column end index
v.push_back(matrix[k][i]); // k is the start row index and m is the end row index
k++;
for(i=k;i<=m;i++)
v.push_back(matrix[i][n]);
n--;
if(m>=k){
for(i=n;i>=l;i--)
v.push_back(matrix[m][i]);
m--;}
if(n>=l){
for(i=m;i>=k;i--)
v.push_back(matrix[i][l]);
l++;}
}
return v;
}
};